description stringlengths 171 4k | code stringlengths 94 3.98k | normalized_code stringlengths 57 4.99k |
|---|---|---|
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
d = {}
a = []
for i in range(n):
x, y = map(int, input().split())
a.append([x, y])
a.sort(key=lambda x: -x[1])
i = 0
reach = False
while i < n:
if a[i][0] == 1 or a[i][1] == n:
j = i + 1
x = a[i][0]
y = a[i][1]
while j < n:
x += 1
y -= 1
if a[j][0] == x and a[j][1] == y:
pass
else:
break
if a[j][0] == n or a[j][1] == 1:
reach = True
j += 1
if reach:
break
i = j
i += 1
if reach:
print("NO")
else:
print("YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR DICT ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR LIST VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER WHILE VAR VAR VAR NUMBER VAR NUMBER IF VAR VAR NUMBER VAR VAR VAR NUMBER VAR IF VAR VAR NUMBER VAR VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER VAR NUMBER IF VAR ASSIGN VAR VAR VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | t = int(input())
for _ in range(t):
n = int(input())
arr = []
for i in range(n):
x, y = map(int, input().split())
arr.append((x, y))
arr.sort()
flag1 = False
for i in range(n):
if arr[i][0] == 1 or arr[i][1] == n:
x = arr[i][0]
y = arr[i][1]
k = i + 1
flag2 = False
for j in range(arr[i][1] - arr[i][0]):
if arr[k] == (x + 1, y - 1):
x += 1
y -= 1
k += 1
continue
else:
flag2 = True
break
if flag2 == False:
flag1 = True
break
if flag1 == False:
print("YES")
else:
print("NO") | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR VAR NUMBER VAR VAR NUMBER IF VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
arr = []
bound = []
ans = 0
for q in range(n):
a, b = map(int, input().split())
arr.append([a - 1, b - 1])
if a == 1 or b == 1 or a == n or b == n:
bound.append([a - 1, b - 1])
i = 0
if n == 2:
if [0, 1] in bound and [1, 0] in bound:
print("NO")
else:
print("YES")
elif (
[1, 0] in bound
and [0, 1] in bound
or [n - 1, n - 2] in bound
and [n - 2, n - 1] in bound
):
print("NO")
else:
arr = sorted(arr)
while i + 1 < len(arr):
x = arr[i][0]
y = arr[i][1]
nx = arr[i + 1][0]
ny = arr[i + 1][1]
if nx == 1 + x and ny + 1 == y:
st = i
while i < len(arr) and nx == 1 + x and ny + 1 == y:
i += 1
x = arr[i][0]
y = arr[i][1]
try:
nx = arr[i + 1][0]
ny = arr[i + 1][1]
except:
break
end = i
if arr[st] in bound and arr[end] in bound:
ans = 1
break
else:
i += 1
if ans == 1:
print("NO")
else:
print("YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR LIST BIN_OP VAR NUMBER BIN_OP VAR NUMBER IF VAR NUMBER VAR NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR LIST BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER IF LIST NUMBER NUMBER VAR LIST NUMBER NUMBER VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING IF LIST NUMBER NUMBER VAR LIST NUMBER NUMBER VAR LIST BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR LIST BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR WHILE BIN_OP VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER IF VAR BIN_OP NUMBER VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR WHILE VAR FUNC_CALL VAR VAR VAR BIN_OP NUMBER VAR BIN_OP VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | t = int(input())
for z in range(t):
n = int(input())
d = dict()
for i in range(n):
j, k = map(int, input().split())
if j + k not in d:
d[j + k] = 1
else:
d[j + k] += 1
n += 1
flag = 0
for i, j in d.items():
if j == i - 1:
print("NO")
flag = 1
break
elif i > n and j == n + n - i - 1:
print("NO")
flag = 1
break
if flag == 0:
print("YES") | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER VAR BIN_OP VAR VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR FUNC_CALL VAR IF VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | def sol(n, blocks):
blocks.sort()
top_left = -1
for i in range(1, n):
if blocks[i][1] == blocks[i - 1][1] - 1:
top_left = i
else:
break
bottom_right = -1
for i in range(n - 2, -1, -1):
if blocks[i][1] == blocks[i + 1][1] + 1:
bottom_right = i
else:
break
if (
top_left != -1
and blocks[top_left][1] == 1
or bottom_right != -1
and blocks[bottom_right][1] == n
):
return "NO"
else:
return "YES"
t = int(input())
while t > 0:
n = int(input())
blocks = []
for i in range(n):
temp = list(map(int, input().split()))
blocks.append(temp)
print(sol(n, blocks))
t = t - 1 | FUNC_DEF EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR VAR IF VAR NUMBER VAR VAR NUMBER NUMBER VAR NUMBER VAR VAR NUMBER VAR RETURN STRING RETURN STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR WHILE VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for t in range(int(input())):
n = int(input())
a = []
for i in range(n):
x, y = map(int, input().split())
b = [x, y]
a.append(b)
a.sort()
x = -(10**9 + 7)
for i in range(1, n):
if a[i][1] == a[i - 1][1] - 1:
x = i
else:
break
y = -(10**9 + 7)
for i in range(n - 2, -1, -1):
if a[i][1] == a[i + 1][1] + 1:
y = i
else:
break
if 0 <= x and x < n and a[x][1] == 1 or 0 <= y and y < n and a[y][1] == n:
print("NO")
else:
print("YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR LIST VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR VAR IF NUMBER VAR VAR VAR VAR VAR NUMBER NUMBER NUMBER VAR VAR VAR VAR VAR NUMBER VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | import sys
from sys import maxsize
def get_ints():
return map(int, sys.stdin.readline().strip().split())
def get_list():
return list(map(int, sys.stdin.readline().strip().split()))
def get_list_string():
return list(map(str, sys.stdin.readline().strip().split()))
def get_string():
return sys.stdin.readline().strip()
def get_int():
return int(sys.stdin.readline().strip())
def get_print_int(x):
sys.stdout.write(str(x) + "\n")
def get_print(x):
sys.stdout.write(x + "\n")
def get_print_int_same(x):
sys.stdout.write(str(x) + " ")
def get_print_same(x):
sys.stdout.write(x + " ")
def subHelper(data, n, ind):
x = data[ind][0]
y = data[ind][1]
if x == 1:
req = y - 1
else:
req = n - x
ind += 1
while req > 0 and ind < n:
if data[ind][0] == x + 1 and data[ind][1] == y - 1:
req -= 1
x = data[ind][0]
y = data[ind][1]
ind += 1
else:
return False
if req == 0:
return True
return False
def helper(data, n):
for i in range(n):
if data[i][0] == 1 or data[i][1] == n:
if subHelper(data, n, i):
return True
return False
def solve():
for _ in range(get_int()):
n = get_int()
data = []
for i in range(n):
data.append(get_list())
data.sort()
if helper(data, n):
get_print("NO")
else:
get_print("YES")
solve() | IMPORT FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR STRING FUNC_DEF EXPR FUNC_CALL VAR BIN_OP VAR STRING FUNC_DEF EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR STRING FUNC_DEF EXPR FUNC_CALL VAR BIN_OP VAR STRING FUNC_DEF ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR NUMBER WHILE VAR NUMBER VAR VAR IF VAR VAR NUMBER BIN_OP VAR NUMBER VAR VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER VAR NUMBER RETURN NUMBER IF VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER NUMBER VAR VAR NUMBER VAR IF FUNC_CALL VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
c = dict()
for i in range(n):
a, b = map(int, input().split())
if a + b in c:
c[a + b] += 1
else:
c[a + b] = 1
fl = 1
for i in range(2, n + 1):
if i in c:
if c[i] == i - 1:
fl = 0
break
j = n + 1
k = n
for i in range(n - 1):
if j in c:
if c[j] == k:
fl = 0
break
j += 1
k -= 1
if fl == 0:
print("NO")
else:
print("YES") | IMPORT ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF BIN_OP VAR VAR VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR IF VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR IF VAR VAR VAR ASSIGN VAR NUMBER VAR NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | t = int(input())
for _ in range(t):
n = int(input())
arr = []
for i in range(n):
arr.append(tuple(map(int, input().split())))
arr.sort()
flag = 1
ans = "YES"
for i in range(1, n):
if arr[i][0] - arr[i - 1][0] == 0:
pass
elif (arr[i][1] - arr[i - 1][1]) / (arr[i][0] - arr[i - 1][0]) not in [
1.0,
-1.0,
]:
flag = 0
if flag == 1:
if arr[i][1] == 1:
ans = "NO"
if flag == 1 and i == n - 1:
ans = "NO"
arr = arr[::-1]
flag = 1
for i in range(1, n):
if arr[i][0] - arr[i - 1][0] == 0:
pass
elif (arr[i][1] - arr[i - 1][1]) / (arr[i][0] - arr[i - 1][0]) not in [
1.0,
-1.0,
]:
flag = 0
if flag == 1:
if arr[i][1] == n:
ans = "NO"
if flag == 1 and i == n - 1:
ans = "NO"
print(ans) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER NUMBER IF BIN_OP BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER LIST NUMBER NUMBER ASSIGN VAR NUMBER IF VAR NUMBER IF VAR VAR NUMBER NUMBER ASSIGN VAR STRING IF VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR STRING ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER NUMBER IF BIN_OP BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER LIST NUMBER NUMBER ASSIGN VAR NUMBER IF VAR NUMBER IF VAR VAR NUMBER VAR ASSIGN VAR STRING IF VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR STRING EXPR FUNC_CALL VAR VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
a = []
for i in range(n):
x, y = map(int, input().split())
a.append([x - 1, y - 1])
a.sort()
z = 1
r = 0
k = a[0][1]
for i in range(n):
if a[i][1] == k:
pass
else:
z = 0
k -= 1
if k < 0:
break
z1 = 1
k = a[n - 1][1]
r1 = 0
for i in range(n - 1, -1, -1):
if a[i][1] == k:
pass
else:
z1 = 0
k += 1
if k >= n:
break
if z == 0 and z1 == 0:
print("YES")
else:
print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR LIST BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER VAR ASSIGN VAR NUMBER VAR NUMBER IF VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR NUMBER VAR ASSIGN VAR NUMBER VAR NUMBER IF VAR VAR IF VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | t = int(input())
for z in range(t):
n = int(input())
points = []
for i in range(n):
points.append(list(map(int, input().split())))
points.sort(key=lambda x: x[0])
flag = True
seq = []
seq_start = 0
for i in range(1, n):
if (
flag
and points[i][1] - points[i - 1][1] == -1
and points[i][0] - points[i - 1][0] == 1
):
continue
if flag:
seq.append([seq_start, i - 1])
seq_start = i
seq.append([seq_start, n - 1])
for sequence in seq:
if points[sequence[0]][0] + points[sequence[1]][1] == 2:
break
if points[sequence[0]][1] + points[sequence[1]][0] == 2 * n:
break
else:
print("YES")
continue
print("NO") | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR LIST ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER NUMBER BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR EXPR FUNC_CALL VAR LIST VAR BIN_OP VAR NUMBER ASSIGN VAR VAR EXPR FUNC_CALL VAR LIST VAR BIN_OP VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR NUMBER NUMBER VAR VAR NUMBER NUMBER NUMBER IF BIN_OP VAR VAR NUMBER NUMBER VAR VAR NUMBER NUMBER BIN_OP NUMBER VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
temp = {}
for i in range(n):
x, y = map(int, input().split())
if int(x + y) in temp:
temp[x + y] += 1
else:
temp[x + y] = 1
flag = 0
if n > 2:
for i in range(3, 2 * n):
if i in temp and temp[i] == min(i - 1, 2 * n - i + 1):
print("NO")
flag = 1
break
if flag == 0:
print("YES")
elif temp[3] == 2:
print("NO")
else:
print("YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF FUNC_CALL VAR BIN_OP VAR VAR VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP NUMBER VAR IF VAR VAR VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP BIN_OP BIN_OP NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING IF VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
xd = [0] * (2 * n)
for _ in range(n):
x, y = map(int, input().split())
xd[x + y] += 1
ans = "YES"
for i in range(3, n + 2):
if xd[i] == i - 1:
ans = "NO"
break
if ans == "YES":
s = n - 1
for i in range(n + 2, 2 * n):
if xd[i] == s:
ans = "NO"
break
s -= 1
print(ans) | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER ASSIGN VAR STRING FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR BIN_OP VAR NUMBER ASSIGN VAR STRING IF VAR STRING ASSIGN VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP NUMBER VAR IF VAR VAR VAR ASSIGN VAR STRING VAR NUMBER EXPR FUNC_CALL VAR VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | from sys import stdin
for i in range(int(stdin.readline())):
n = int(stdin.readline())
h = {}
for j in range(n):
x, y = map(int, stdin.readline().split())
if x + y not in h:
h[x + y] = 1
else:
h[x + y] += 1
flag = 1
for g in h.keys():
if g <= n + 1 and h[g] == g - 1:
flag = 0
if g > n + 1 and h[g] == 2 * n + 1 - g:
flag = 0
if flag == 0:
print("NO")
else:
print("YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER VAR BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR IF VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR VAR BIN_OP BIN_OP BIN_OP NUMBER VAR NUMBER VAR ASSIGN VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | def main():
t = int(input())
while t > 0:
n = int(input())
fmap = [(0) for i in range(2 * n)]
for i in range(n):
c = input().split()
row = int(c[0])
col = int(c[1])
fmap[row + col] += 1
left = 3
right = 2 * n - 1
val = 2
ans = False
while left <= right:
if fmap[left] == val or fmap[right] == val:
ans = True
break
else:
left += 1
right -= 1
val += 1
if ans:
print("NO")
else:
print("YES")
t -= 1
main() | FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR WHILE VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR BIN_OP NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER VAR BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING VAR NUMBER EXPR FUNC_CALL VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
l = []
flag = 0
ref = list(map(int, "0" * (2 * n + 1)))
for i in range(n):
l.append(sum(map(int, input().split())))
for i in range(n):
ref[l[i]] += 1
for i in range(2, n + 2):
if ref[i] == i - 1:
flag = 1
break
for i in range(n + 2, 2 * n):
if ref[i] == n - i % n + 1:
flag = 1
break
print("NO" if flag else "YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR BIN_OP STRING BIN_OP BIN_OP NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP NUMBER VAR IF VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR STRING STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | def sol(d, n):
i = 1
while d[i] == d[i + 1] + 1:
i += 1
if i == n:
break
if d[i] == 1:
return "NO"
i = n
while d[i] == d[i - 1] - 1:
i -= 1
if i == 1:
break
if d[i] == n:
return "NO"
return "YES"
for _ in range(int(input())):
n = int(input())
d = {}
for i in range(n):
X, Y = map(int, input().split())
d[Y] = X
print(sol(d, n)) | FUNC_DEF ASSIGN VAR NUMBER WHILE VAR VAR BIN_OP VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER IF VAR VAR IF VAR VAR NUMBER RETURN STRING ASSIGN VAR VAR WHILE VAR VAR BIN_OP VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER IF VAR NUMBER IF VAR VAR VAR RETURN STRING RETURN STRING FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | import sys
for t in range(int(input())):
n = int(input())
d = set()
for i in range(n):
a, b = map(int, input().split())
d.add((a, b))
t = False
for j in range(2, n + 1):
if (1, j) in d:
flag = 1
i = 1
k = j
while flag:
if k == 0:
t = True
break
elif (i, k) not in d:
break
else:
i += 1
k -= 1
break
if t:
print("NO")
else:
for i in range(1, n):
if (i, n) in d:
j = i
k = n
while 1:
if j > n:
t = True
break
elif (j, k) not in d:
break
else:
j += 1
k -= 1
break
if t:
print("NO")
else:
print("YES") | IMPORT FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF NUMBER VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR IF VAR NUMBER ASSIGN VAR NUMBER IF VAR VAR VAR VAR NUMBER VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR WHILE NUMBER IF VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR VAR NUMBER VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
d = {}
for i in range(n):
x, y = map(int, input().split())
val = y - 1
if x + val <= n:
if d.get(x + val) is None:
d[x + val] = 1
else:
d[x + val] += 1
else:
val = y - (n - x)
if d.get(n + val - 1) is None:
d[n + val - 1] = 1
else:
d[n + val - 1] += 1
flag = True
for i in range(2, n + 1):
if d.get(i) is not None and d[i] == i:
flag = False
break
k = n - 1
for i in range(n + 1, n + n - 1):
if d.get(i) is not None and d[i] == k:
flag = False
break
k -= 1
if flag:
print("YES")
else:
print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER IF BIN_OP VAR VAR VAR IF FUNC_CALL VAR BIN_OP VAR VAR NONE ASSIGN VAR BIN_OP VAR VAR NUMBER VAR BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP VAR VAR IF FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER NONE ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR NONE VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR NONE VAR VAR VAR ASSIGN VAR NUMBER VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | from sys import stdin
def solve():
for _ in range(int(stdin.readline().strip())):
N = int(stdin.readline().rstrip())
Y = [0] * N
for _ in range(N):
x, y = map(int, stdin.readline().rstrip().split())
Y[x - 1] = y
pos = 1
ranges = [(1, Y[0])]
_pass = 0
for y in Y[1:]:
if _pass:
continue
if y > pos:
if y < N and ranges[0][1] - 1 > y:
ranges = [(pos, y), (y + 1, N + 1)]
else:
tmp = 0
if ranges[-1][1] - 1 > y:
tmp = max(ranges[-1][0], y + 1), N + 1
ranges = [(pos, y)]
if tmp:
ranges.append(tmp)
elif y < pos:
continue
elif y < ranges[0][1] - 1:
ranges = [(max(y + 1, ranges[0][0]), N + 1)]
pos = ranges[0][0]
elif y < ranges[-1][1] - 1:
ranges = [(max(y + 1, ranges[-1][0]), N + 1)]
pos = ranges[0][0]
else:
found = 0
for i, j in ranges:
if y + 1 in range(i, j):
pos = y + 1
ranges = [(pos, N + 1)]
found = 1
break
if not found:
_pass = 1
continue
ans = "NO"
if not _pass:
for i, j in ranges:
if N in range(i, j):
ans = "YES"
print(ans)
solve() | FUNC_DEF FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR LIST NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR NUMBER IF VAR IF VAR VAR IF VAR VAR BIN_OP VAR NUMBER NUMBER NUMBER VAR ASSIGN VAR LIST VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF BIN_OP VAR NUMBER NUMBER NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER NUMBER BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR LIST VAR VAR IF VAR EXPR FUNC_CALL VAR VAR IF VAR VAR IF VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR LIST FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER IF VAR BIN_OP VAR NUMBER NUMBER NUMBER ASSIGN VAR LIST FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR IF BIN_OP VAR NUMBER FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR LIST VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF VAR ASSIGN VAR NUMBER ASSIGN VAR STRING IF VAR FOR VAR VAR VAR IF VAR FUNC_CALL VAR VAR VAR ASSIGN VAR STRING EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | from sys import stdin
input = stdin.readline
def down(i, j):
count = 0
while i <= n and j > 0 and pos.get((i, j), False):
count += 1
i, j = i + 1, j - 1
return count
def up(i, j):
count = 0
while i > 0 and j <= n and pos.get((i, j), False):
count += 1
i, j = i - 1, j + 1
return count
def answer():
count1 = down(root1[0], root1[1])
value1 = root1[1]
count2 = up(root2[0], root2[1])
value2 = n + 1 - root2[1]
if count1 == value1 or count2 == value2:
return "NO"
return "YES"
for T in range(int(input())):
n = int(input())
pos = dict()
for i in range(n):
x, y = map(int, input().split())
pos[x, y] = True
if x == 1:
root1 = [x, y]
if x == n:
root2 = [x, y]
print(answer()) | ASSIGN VAR VAR FUNC_DEF ASSIGN VAR NUMBER WHILE VAR VAR VAR NUMBER FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR NUMBER WHILE VAR NUMBER VAR VAR FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR VAR VAR RETURN STRING RETURN STRING FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR LIST VAR VAR IF VAR VAR ASSIGN VAR LIST VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
n = int(input())
b = []
for i in range(n):
b.append([int(i) for i in input().split()])
b.sort(key=lambda x: x[1])
d = 0
i = 0
while True:
if b[i][0] == 1:
d = 1
break
if b[i][0] == b[i + 1][0] + 1:
i += 1
else:
break
if d == 1:
print("NO")
continue
b.sort(key=lambda x: -x[0])
i = 0
while True:
if b[i][1] == n:
d = 1
break
if b[i][1] == b[i + 1][1] - 1:
i += 1
else:
break
if d == 1:
print("NO")
continue
print("YES") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE NUMBER IF VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER IF VAR VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE NUMBER IF VAR VAR NUMBER VAR ASSIGN VAR NUMBER IF VAR VAR NUMBER BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | t = int(input())
def f(tup):
return tup[0]
for _ in range(t):
n = int(input())
blocks = []
for i in range(n):
a, b = map(int, input().split())
blocks.append((a, b))
blocks.sort(key=f)
start = True
no = False
for i in range(1, n):
if start:
if blocks[i][1] + 1 == blocks[i - 1][1]:
if blocks[i][0] == n or blocks[i][1] == 1:
no = True
break
else:
start = False
if blocks[i][1] == n:
start = True
if no:
print("NO")
else:
print("YES") | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_DEF RETURN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR IF BIN_OP VAR VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR NUMBER VAR VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER IF VAR VAR NUMBER VAR ASSIGN VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | for _ in range(int(input())):
N = int(input())
ans = True
G = [0] * (2 * N - 3)
for i in range(N):
X, Y = map(int, input().split())
if ans:
j = X + Y - 3
G[j] += 1
if G[j] == N - abs(X + Y - N - 1):
ans = False
print("YES" if ans else "NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR NUMBER IF VAR VAR BIN_OP VAR FUNC_CALL VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR STRING STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | t = int(input())
for _ in range(t):
n = int(input())
blocks1 = []
blockset = set()
for _1 in range(n):
x, y = map(int, input().split())
blocks1.append((x, y))
blockset.add((x, y))
blocks1.sort()
x, y = blocks1[0]
while (x + 1, y - 1) in blockset:
x += 1
y -= 1
if y == 1:
print("NO")
else:
x, y = blocks1[-1]
while (x - 1, y + 1) in blockset:
x -= 1
y += 1
if y == n:
print("NO")
else:
print("YES") | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR VAR VAR NUMBER WHILE BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR VAR NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR VAR NUMBER WHILE BIN_OP VAR NUMBER BIN_OP VAR NUMBER VAR VAR NUMBER VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Read problem statements in [Mandarin], [Bengali], and [Russian] as well.
You are given a positive integer N. Consider a square grid of size N \times N, with rows numbered 1 to N from top to bottom and columns numbered 1 to N from left to right. Initially you are at (1,1) and you have to reach (N,N). From a cell you can either move one cell to the right or one cell down (if possible). Formally, if you are at (i,j), then you can either move to (i+1,j) if i < N, or to (i,j+1) if j < N.
There are exactly N blocks in the grid, such that each row contains exactly one block and each column contains exactly one block. You can't move to a cell which contains a block. It is guaranteed that blocks will not placed in (1,1) and (N,N).
You have to find out whether you can reach (N,N).
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains N - the size of the square grid.
- The i-th line of the next N lines contains two integers X_{i} and Y_{i} indicating that (X_{i}, Y_{i}) is the position of a block in the grid.
------ Output Format ------
For each test case, if there exists a path from (1,1) to (N,N), output YES, otherwise output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
------ Constraints ------
$1 ≤T ≤1000$
$2 ≤N ≤10^{6}$
$1 ≤X_{i},Y_{i} ≤N$
$(X_{i}, Y_{i}) \ne (1, 1)$ and $(X_{i}, Y_{i}) \ne (N, N)$ for all $1 ≤i ≤N$
$X_{i} \ne X_{j}$ and $Y_{i} \ne Y_{j}$ for all $1 ≤i < j ≤N$
- Sum of $N$ over all test cases does not exceed $10^{6}$
----- Sample Input 1 ------
2
3
1 2
2 3
3 1
2
1 2
2 1
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
- Test case $1$: We can follow the path $(1,1) \to (2,1) \to (2,2) \to (3,2) \to (3,3)$.
- Test case $2$: We can't move from the starting point, so it is impossible to reach $(N, N)$. | def max_diag_len(coord_sum, n):
if coord_sum <= n + 1:
return coord_sum - 1
else:
return 2 * n - coord_sum + 1
def main():
t = int(input())
for case_idx in range(t):
n = int(input())
coord_sums = [0] * (2 * n)
can_cross = True
for coord_idx in range(n):
i, j = [int(x) for x in input().split()]
coord_sums[i + j] += 1
if coord_sums[i + j] >= max_diag_len(i + j, n):
can_cross = False
if can_cross:
print("YES")
else:
print("NO")
main() | FUNC_DEF IF VAR BIN_OP VAR NUMBER RETURN BIN_OP VAR NUMBER RETURN BIN_OP BIN_OP BIN_OP NUMBER VAR VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR VAR BIN_OP VAR VAR NUMBER IF VAR BIN_OP VAR VAR FUNC_CALL VAR BIN_OP VAR VAR VAR ASSIGN VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
deltaDic = {"minute": 60, "hour": 3600, "day": 24 * 3600}
def __init__(self):
self.tweetDic = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if not tweetName in self.tweetDic:
self.tweetDic[tweetName] = []
self.tweetDic[tweetName].append(time)
self.tweetDic[tweetName].sort()
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if not tweetName in self.tweetDic:
return []
delta = self.deltaDic[freq]
output = [0] * ((endTime - startTime) // delta + 1)
for t in self.tweetDic[tweetName]:
if t < startTime:
continue
elif t > endTime:
continue
else:
idx = (t - startTime) // delta
output[idx] += 1
return output | CLASS_DEF ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER BIN_OP NUMBER NUMBER FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR IF VAR VAR ASSIGN VAR VAR LIST EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR VAR RETURN LIST ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER FOR VAR VAR VAR IF VAR VAR IF VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.d = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName not in self.d:
self.d[tweetName] = [time]
else:
self.d[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if freq == "minute":
s = 60
elif freq == "hour":
s = 3600
else:
s = 3600 * 24
intervals = (endTime - startTime) // s + 1
res = [0] * intervals
times = self.d[tweetName]
for t in times:
if startTime <= t <= endTime:
i = (t - startTime) // s
res[i] += 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR IF VAR VAR ASSIGN VAR VAR LIST VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR STRING ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR BIN_OP NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR VAR VAR FOR VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.recorder = collections.defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
bisect.insort(self.recorder[tweetName], time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
delta = 60 if freq == "minute" else 3600 if freq == "hour" else 86400
res, i, start = [], 1, startTime
while start <= endTime:
end = min(startTime + delta * i, endTime + 1)
res.append(
bisect_left(self.recorder[tweetName], end)
- bisect_left(self.recorder[tweetName], start)
)
start, i = end, i + 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR STRING NUMBER VAR STRING NUMBER NUMBER ASSIGN VAR VAR VAR LIST NUMBER VAR WHILE VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR BIN_OP VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName in list(self.tweets.keys()):
bisect.insort(self.tweets[tweetName], time)
else:
self.tweets[tweetName] = [time]
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if tweetName not in self.tweets:
return []
delta = 60 if freq == "minute" else 3600 if freq == "hour" else 86400
time_list = self.tweets[tweetName]
size = int((endTime - startTime) // delta) + 1
res = [0] * size
for t in time_list:
if startTime <= t <= endTime:
index = int((t - startTime) // delta)
res[index] += 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR IF VAR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR LIST VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR VAR RETURN LIST ASSIGN VAR VAR STRING NUMBER VAR STRING NUMBER NUMBER ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR IF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
FREQUENCE = {"minute": 60, "hour": 3600, "day": 24 * 3600}
def __init__(self):
self.tweets_dict = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName not in self.tweets_dict:
self.tweets_dict[tweetName] = []
bisect.insort(self.tweets_dict.get(tweetName), time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if tweetName not in self.tweets_dict:
return []
delta = TweetCounts.FREQUENCE[freq]
num_intervals = (endTime - startTime) // delta + 1
result = [0] * num_intervals
start = bisect.bisect_left(self.tweets_dict.get(tweetName), startTime)
end = bisect.bisect_right(self.tweets_dict.get(tweetName), endTime)
for t1 in range(start - 1, end + 1):
if t1 < 0:
continue
if t1 >= len(self.tweets_dict.get(tweetName)):
continue
t = self.tweets_dict.get(tweetName)[t1]
if t < startTime or t > endTime:
continue
index = (t - startTime) // delta
result[index] += 1
return result | CLASS_DEF ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER BIN_OP NUMBER NUMBER FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR IF VAR VAR ASSIGN VAR VAR LIST EXPR FUNC_CALL VAR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR VAR RETURN LIST ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER IF VAR NUMBER IF VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
self.tweets[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
count = 0
den = 0
size = 0
if freq == "minute":
den = 60
size = (endTime - startTime) // 60 + 1
elif freq == "hour":
den = 3600
size = (endTime - startTime) // 3600 + 1
else:
den = 86400
size = (endTime - startTime) // 86400 + 1
op = [0] * size
for t in self.tweets[tweetName]:
if startTime <= t and t <= endTime:
idx = (t - startTime) // den
op[idx] += 1
return op | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = collections.defaultdict(list)
self.convert = {"minute": 60, "hour": 3600, "day": 86400}
def recordTweet(self, tweetName: str, time: int) -> None:
self.tweets[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
seconds = self.convert[freq]
ans = [0] * ((endTime - startTime) // seconds + 1)
for time in self.tweets[tweetName]:
if startTime <= time <= endTime:
ans[(time - startTime) // seconds] += 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER NUMBER FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER FOR VAR VAR VAR IF VAR VAR VAR VAR BIN_OP BIN_OP VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = defaultdict(list)
self.mapping = {"minute": 60, "hour": 3600, "day": 86400}
def binary_search(self, left, right, key, array, type):
while left <= right:
mid = left + (right - left) // 2
if array[mid] >= key:
right = mid - 1
else:
left = mid + 1
return left if type == "S" else right
def recordTweet(self, tweetName: str, time: int) -> None:
self.tweets[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
self.tweets[tweetName].sort()
tweetcounts = self.tweets[tweetName]
intervals = []
while startTime < endTime + 1:
startindex = self.binary_search(
0, len(tweetcounts) - 1, startTime, tweetcounts, "S"
)
findval = min(startTime + self.mapping[freq], endTime + 1)
endindex = self.binary_search(
0, len(tweetcounts) - 1, findval, tweetcounts, "E"
)
intervals.append(endindex - startindex + 1)
startTime += self.mapping[freq]
return intervals | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER NUMBER FUNC_DEF WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR STRING VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR LIST WHILE VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR STRING ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR STRING EXPR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.log = defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
self.log[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
ret = []
events = sorted([t for t in self.log[tweetName] if startTime <= t <= endTime])
ei = 0
time = startTime
delta = {"minute": 60, "hour": 3600, "day": 24 * 3600}[freq]
cur = 0
while time <= endTime:
if ei == len(events):
ret.append(cur)
cur = 0
time += delta
continue
if events[ei] < time:
ei += 1
elif time + delta <= events[ei]:
ret.append(cur)
time += delta
cur = 0
else:
assert time <= events[ei] < time + delta
cur += 1
ei += 1
return ret | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER BIN_OP NUMBER NUMBER VAR ASSIGN VAR NUMBER WHILE VAR VAR IF VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR VAR IF VAR VAR VAR VAR NUMBER IF BIN_OP VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR NUMBER VAR VAR VAR BIN_OP VAR VAR VAR NUMBER VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.memo = collections.defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
self.memo[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
lst = self.memo[tweetName]
lst = [(t - startTime) for t in lst if t >= startTime and t <= endTime]
if freq == "minute":
freq = 60
elif freq == "hour":
freq = 60 * 60
elif freq == "day":
freq = 24 * 60 * 60
length, remainder = divmod(endTime - startTime + 1, freq)
if remainder > 0:
length += 1
res = [(0) for _ in range(length)]
for t in lst:
res[t // freq] += 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR IF VAR STRING ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR BIN_OP NUMBER NUMBER IF VAR STRING ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER ASSIGN VAR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER VAR IF VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR VAR VAR BIN_OP VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
FREQUENCE = {"minute": 60, "hour": 3600, "day": 24 * 3600}
def __init__(self):
self.tweets_dict = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName not in self.tweets_dict:
self.tweets_dict[tweetName] = []
left, right = 0, len(self.tweets_dict[tweetName])
while left < right:
mid = left + (right - left) // 2
if self.tweets_dict[tweetName][mid] == time:
right = mid
elif self.tweets_dict[tweetName][mid] > time:
right = mid
elif self.tweets_dict[tweetName][mid] < time:
left = mid + 1
self.tweets_dict[tweetName].insert(left, time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if tweetName not in self.tweets_dict:
return []
delta = TweetCounts.FREQUENCE[freq]
num_intervals = (endTime - startTime) // delta + 1
result = [0] * num_intervals
for t in self.tweets_dict[tweetName]:
if t < startTime:
continue
if t > endTime:
break
index = (t - startTime) // delta
result[index] += 1
return result | CLASS_DEF ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER BIN_OP NUMBER NUMBER FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR IF VAR VAR ASSIGN VAR VAR LIST ASSIGN VAR VAR NUMBER FUNC_CALL VAR VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR VAR RETURN LIST ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR VAR IF VAR VAR IF VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.a = collections.defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
heapq.heappush(self.a[tweetName], time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if tweetName not in self.a:
return []
temp = list(self.a[tweetName])
q = []
while temp:
q.append(heapq.heappop(temp))
if freq == "minute":
f = 60
elif freq == "hour":
f = 3600
else:
f = 3600 * 24
bucket_size = (endTime - startTime) // f + 1
ans = [0] * bucket_size
cur = 0
end = f + startTime
for t in q:
if t < startTime:
continue
if t > endTime:
break
i = (t - startTime) // f
ans[i] += 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR VAR RETURN LIST ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR LIST WHILE VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR STRING ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR BIN_OP NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR VAR FOR VAR VAR IF VAR VAR IF VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.data = defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
self.data[tweetName].append(time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if freq[0] == "m":
ans = [0] * ((endTime - startTime) // 60 + 1)
for x in self.data[tweetName]:
if startTime <= x <= endTime:
a = (x - startTime) // 60
ans[a] += 1
return ans
elif freq[0] == "h":
ans = [0] * ((endTime - startTime) // 3600 + 1)
for x in self.data[tweetName]:
if startTime <= x <= endTime:
a = (x - startTime) // 3600
ans[a] += 1
return ans
else:
ans = [0] * ((endTime - startTime) // 86400 + 1)
for x in self.data[tweetName]:
if startTime <= x <= endTime:
a = (x - startTime) // 86400
ans[a] += 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR NUMBER STRING ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER FOR VAR VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR NUMBER RETURN VAR IF VAR NUMBER STRING ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER FOR VAR VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR NUMBER RETURN VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP VAR VAR NUMBER NUMBER FOR VAR VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tw = collections.defaultdict(list)
self.duration = {"minute": 60, "hour": 3600, "day": 86400}
def recordTweet(self, tweetName: str, time: int) -> None:
if not self.tw[tweetName]:
self.tw[tweetName].append(time)
else:
ind = bisect.bisect(self.tw[tweetName], time)
self.tw[tweetName] = (
self.tw[tweetName][:ind] + [time] + self.tw[tweetName][ind:]
)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
res = []
q = self.tw[tweetName]
s = startTime
while s <= endTime:
e = min(endTime, s + self.duration[freq] - 1)
ind1 = bisect.bisect_left(q, s)
ind2 = bisect.bisect_right(q, e, lo=ind1)
res.append(ind2 - ind1)
s = e + 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER NUMBER FUNC_DEF VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR BIN_OP BIN_OP VAR VAR VAR LIST VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR FUNC_CALL VAR VAR BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
FREQUENCEY_TO_SECONDS = {"minute": 60, "hour": 3600, "day": 86400}
def __init__(self):
self._data = collections.defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
bisect.insort(self._data[tweetName], time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
delta = self.FREQUENCEY_TO_SECONDS.get(freq.lower(), None)
if not delta:
return []
i, result = startTime, []
while i <= endTime:
j = min(i + delta, endTime + 1)
left = bisect.bisect_left(self._data[tweetName], j)
right = bisect.bisect_left(self._data[tweetName], i)
result.append(left - right)
i += delta
return result | CLASS_DEF ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR NONE IF VAR RETURN LIST ASSIGN VAR VAR VAR LIST WHILE VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
insort(self.tweets[tweetName], time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
delta = 60
if freq == "hour":
delta = 3600
elif freq == "day":
delta = 86400
pre = bisect_left(self.tweets[tweetName], startTime)
n = (endTime + 1 - startTime) // delta + (
1 if (endTime + 1 - startTime) % delta != 0 else 0
)
end, res = startTime, []
for _ in range(n):
end = min(end + delta, endTime + 1)
i = bisect_left(self.tweets[tweetName], end)
res.append(i - pre)
pre = i
return res | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP BIN_OP VAR NUMBER VAR VAR BIN_OP BIN_OP BIN_OP VAR NUMBER VAR VAR NUMBER NUMBER NUMBER ASSIGN VAR VAR VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.data = collections.defaultdict(dict)
def recordTweet(self, tweetName: str, time: int) -> None:
if time not in self.data[tweetName]:
self.data[tweetName][time] = 1
else:
self.data[tweetName][time] += 1
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
delta = [60, 60 * 60, 60 * 60 * 24]
if freq == "minute":
t = delta[0]
elif freq == "hour":
t = delta[1]
else:
t = delta[2]
res = [0] * ((endTime - startTime) // t + 1)
i = 0
data = self.data[tweetName]
for time in sorted(data.keys()):
if startTime <= time <= endTime:
res[(time - startTime) // t] += data[time]
return res | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR NUMBER VAR VAR VAR NUMBER NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR LIST NUMBER BIN_OP NUMBER NUMBER BIN_OP BIN_OP NUMBER NUMBER NUMBER IF VAR STRING ASSIGN VAR VAR NUMBER IF VAR STRING ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR IF VAR VAR VAR VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = collections.defaultdict(list)
def __bs(self, arr, val):
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] >= val:
hi = mid
else:
lo = mid + 1
return lo
def recordTweet(self, tweetName: str, time: int) -> None:
idx = self.__bs(self.tweets[tweetName], time)
self.tweets[tweetName].insert(idx, time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
delta = 60 if freq == "minute" else 3600 if freq == "hour" else 86400
i = startTime
arr = self.tweets[tweetName]
result = []
while i <= endTime:
j = min(i + delta, endTime + 1)
result.append(self.__bs(arr, j) - self.__bs(arr, i))
i += delta
return result | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR NUMBER FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR STRING NUMBER VAR STRING NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR LIST WHILE VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
MAP = {"minute": 60, "hour": 60 * 60, "day": 24 * 60 * 60}
def __init__(self):
self.data = defaultdict(list)
def recordTweet(self, tweetName: str, time: int) -> None:
self.data[tweetName].append(time)
self.data[tweetName].sort()
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
data = self.data[tweetName]
index = 0
while index < len(data) and data[index] < startTime:
index += 1
ans = []
tmp = 0
k = 0
delta = self.MAP[freq]
while startTime + k * delta <= endTime:
end = min(startTime + delta * (k + 1), endTime + 1)
if index >= len(data) or data[index] >= end:
ans.append(tmp)
tmp = 0
k += 1
else:
tmp += 1
index += 1
return ans | CLASS_DEF ASSIGN VAR DICT STRING STRING STRING NUMBER BIN_OP NUMBER NUMBER BIN_OP BIN_OP NUMBER NUMBER NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR LIST ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR VAR WHILE BIN_OP VAR BIN_OP VAR VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR BIN_OP VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER IF VAR FUNC_CALL VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.store = defaultdict(list)
self.delta = {"hour": 3600, "minute": 60, "day": 24 * 3600}
def recordTweet(self, tn: str, time: int) -> None:
insort(self.store[tn], time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
d = self.delta[freq]
ans = []
arr = self.store[tweetName]
for st_time in range(startTime, endTime + 1, d):
left = bisect_left(arr, st_time)
right = bisect_right(arr, min(endTime, st_time + d - 1))
ans.append(right - left)
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT STRING STRING STRING NUMBER NUMBER BIN_OP NUMBER NUMBER FUNC_DEF VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR BIN_OP BIN_OP VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweet2time = {}
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName not in self.tweet2time:
self.tweet2time[tweetName] = [time]
else:
arr = self.tweet2time[tweetName]
index = self.binary_search(arr, time)
arr.insert(index, time)
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
if tweetName not in self.tweet2time:
return []
arr = self.tweet2time[tweetName]
if freq == "minute":
interval = 60
elif freq == "hour":
interval = 3600
else:
interval = 3600 * 60
time = startTime
result = []
while time <= endTime:
end_time = time + interval
start_index = self.binary_search(arr, time)
end_index = self.binary_search(arr, min(end_time, endTime + 1))
result.append(end_index - start_index)
time = end_time
return result
def binary_search(self, arr, num):
left = 0
right = len(arr)
while left < right:
mid = left + (right - left) // 2
if arr[mid] > num:
right = mid
elif arr[mid] < num:
left = mid + 1
else:
return mid
return left | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR IF VAR VAR ASSIGN VAR VAR LIST VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR NONE FUNC_DEF VAR VAR VAR VAR IF VAR VAR RETURN LIST ASSIGN VAR VAR VAR IF VAR STRING ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR BIN_OP NUMBER NUMBER ASSIGN VAR VAR ASSIGN VAR LIST WHILE VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR RETURN VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR RETURN VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweetDict = {}
def insertAt(self, tN, x):
l = 0
r = len(self.tweetDict[tN]) - 1
if x < self.tweetDict[tN][l]:
return 0
if x > self.tweetDict[tN][r]:
return r + 1
while r > l:
m = (r + l) // 2
if self.tweetDict[tN][m] < x:
l = m + 1
else:
r = m
return l
def recordTweet(self, tweetName: str, time: int) -> None:
if tweetName in self.tweetDict:
self.tweetDict[tweetName].insert(self.insertAt(tweetName, time), time)
else:
self.tweetDict[tweetName] = [time]
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
ans = []
if freq == "minute":
delta = 60
elif freq == "hour":
delta = 3600
else:
delta = 86400
total = (endTime - startTime) // delta
if (endTime - startTime) % delta > 0:
total += 1
n = 0
for t in range(startTime, endTime + 1, delta):
t0 = t
t1 = min(t + delta, endTime + 1)
i0 = self.insertAt(tweetName, t0)
if i0 == len(self.tweetDict[tweetName]):
ans += [0] * (total - n)
return ans
i1 = self.insertAt(tweetName, t1)
if i1 == len(self.tweetDict[tweetName]):
ans.append(i1 - i0)
ans += [0] * (total - n - 1)
return ans
n += 1
ans.append(i1 - i0)
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR VAR VAR RETURN NUMBER IF VAR VAR VAR VAR RETURN BIN_OP VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR RETURN VAR FUNC_DEF VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR LIST VAR NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR LIST IF VAR STRING ASSIGN VAR NUMBER IF VAR STRING ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR IF BIN_OP BIN_OP VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR FUNC_CALL VAR VAR VAR VAR BIN_OP LIST NUMBER BIN_OP VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR VAR VAR BIN_OP LIST NUMBER BIN_OP BIN_OP VAR VAR NUMBER RETURN VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR RETURN VAR VAR VAR |
Implement the class TweetCounts that supports two methods:
1. recordTweet(string tweetName, int time)
Stores the tweetName at the recorded time (in seconds).
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Returns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).
freq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.
The first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).
Example:
Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]
Output
[null,null,null,null,[2],[2,1],null,[4]]
Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0);
tweetCounts.recordTweet("tweet3", 60);
tweetCounts.recordTweet("tweet3", 10); // All tweets correspond to "tweet3" with recorded times at 0, 10 and 60.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.
tweetCounts.recordTweet("tweet3", 120); // All tweets correspond to "tweet3" with recorded times at 0, 10, 60 and 120.
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.
Constraints:
There will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.
0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4 | class TweetCounts:
def __init__(self):
self.tweets = {}
def recordTweet(self, tweetName: str, time: int) -> None:
self.tweets.setdefault(tweetName, {}).setdefault(time, 0)
self.tweets[tweetName][time] += 1
def getTweetCountsPerFrequency(
self, freq: str, tweetName: str, startTime: int, endTime: int
) -> List[int]:
eligible = []
for time, count in list(self.tweets.get(tweetName, {}).items()):
if startTime <= time <= endTime:
eligible.append((time, count))
if "minute" == freq:
samples = 60
elif "hour" == freq:
samples = 3600
elif "day" == freq:
samples = 86400
else:
raise RuntimeError(freq)
num_results = 1 + (endTime - startTime) // samples
results = [0] * num_results
for time, count in eligible:
offset = time - startTime
if "minute" == freq:
offset //= 60
elif "hour" == freq:
offset //= 3600
elif "day" == freq:
offset //= 86400
results[offset] += count
return results | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF VAR VAR EXPR FUNC_CALL FUNC_CALL VAR VAR DICT VAR NUMBER VAR VAR VAR NUMBER NONE FUNC_DEF VAR VAR VAR VAR ASSIGN VAR LIST FOR VAR VAR FUNC_CALL VAR FUNC_CALL FUNC_CALL VAR VAR DICT IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF STRING VAR ASSIGN VAR NUMBER IF STRING VAR ASSIGN VAR NUMBER IF STRING VAR ASSIGN VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP NUMBER BIN_OP BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR IF STRING VAR VAR NUMBER IF STRING VAR VAR NUMBER IF STRING VAR VAR NUMBER VAR VAR VAR RETURN VAR VAR VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def check(self, N, K, arr, mid):
st = 0
cow = 1
for i in arr:
if st + i <= mid:
st += i
else:
cow += 1
if cow > K or i > mid:
return False
st = i
return True
def splitArray(self, arr, N, K):
s = 0
e = sum(arr)
mid = s + (e - s) // 2
ans = -1
while s <= e:
if self.check(N, K, arr, mid) == True:
ans = mid
e = mid - 1
else:
s = mid + 1
mid = s + (e - s) // 2
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR RETURN NUMBER ASSIGN VAR VAR RETURN NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF FUNC_CALL VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
left, right = max(arr), sum(arr)
res = right
def canSplit(largest):
subarray = 1
currSum = 0
for num in arr:
currSum += num
if currSum > largest:
currSum = num
subarray += 1
return subarray <= K
while left <= right:
mid = (left + right) // 2
if canSplit(mid):
res = mid
right = mid - 1
else:
left = mid + 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER RETURN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def cansplit(m):
nonlocal K, arr
s = 0
cnt = 1
for i in arr:
s += i
if s > m:
cnt += 1
s = i
return cnt <= K
lo, hi = max(arr), sum(arr) + 1
while lo < hi:
mi = lo + (hi - lo) // 2
if cansplit(mi):
hi = mi
else:
lo = mi + 1
return lo | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR RETURN VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
l = None
r = 0
ans = 0
for x in arr:
if l is None:
l = x
else:
l = max(l, x)
r += x
while l <= r:
mid = (l + r) // 2
num = 0
cursum = 0
maxsum = 0
for x in arr:
if cursum + x <= mid:
cursum += x
else:
num += 1
cursum = x
num += 1
if num <= K:
ans = mid
r = mid - 1
else:
l = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NONE ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF VAR NONE ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def findPartitions(self, arr, ans, n):
k = 1
rem_ans = ans
for i in range(n):
if arr[i] <= rem_ans:
rem_ans = rem_ans - arr[i]
else:
k = k + 1
rem_ans = ans
rem_ans = rem_ans - arr[i]
return k
def splitArray(self, arr, n, k):
ans = None
maximum_element = arr[0]
TotalSum = arr[0]
for i in range(1, n):
if maximum_element < arr[i]:
maximum_element = arr[i]
TotalSum += arr[i]
start = maximum_element
end = TotalSum
while start <= end:
mid = (start + end) // 2
partitions = self.findPartitions(arr, mid, n)
if partitions <= k:
ans = mid
end = mid - 1
else:
start = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR NONE ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR IF VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def checkPartition(arr, partsum):
sum1 = 0
count = 1
for i in arr:
if sum1 + i > partsum:
count = count + 1
sum1 = i
continue
sum1 = sum1 + i
if count <= K:
return True
return False
i, j = max(arr), sum(arr)
res = -1
while j >= i:
mid = (i + j) // 2
x = checkPartition(arr, mid)
if x:
res = mid
j = mid - 1
else:
i = mid + 1
return res | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR VAR IF VAR VAR RETURN NUMBER RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def valid(self, mid, arr, N, K):
count = 0
ssum = 0
for i in range(N):
if arr[i] > mid:
return False
ssum += arr[i]
if ssum > mid:
count += 1
ssum = arr[i]
count += 1
if count <= K:
return True
return False
def splitArray(self, arr, N, K):
start = max(arr)
end = sum(arr)
ans = 0
while start <= end:
mid = (start + end) // 2
if self.valid(mid, arr, N, K):
ans = mid
end = mid - 1
else:
start = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN NUMBER VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR RETURN NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def __init__(self):
self.res = -10000
def binary_search(self, arr, sum_search):
subarray = 0
sum1 = 0
for num in arr:
sum1 += num
if sum1 > sum_search:
subarray += 1
sum1 = num
return subarray + 1 <= self.K
def recursion(self, arr):
if self.res != -10000:
return
if self.low > self.high:
self.res = self.low
return
sum_search = self.low + self.high >> 1
if self.binary_search(arr, sum_search):
self.high = sum_search - 1
self.recursion(arr)
else:
self.low = sum_search + 1
self.recursion(arr)
return
def splitArray(self, arr, N, K):
self.K = K
if K == 1:
return sum(arr)
self.low = max(arr)
self.high = sum(arr)
self.recursion(arr)
return self.res | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR RETURN BIN_OP VAR NUMBER VAR FUNC_DEF IF VAR NUMBER RETURN IF VAR VAR ASSIGN VAR VAR RETURN ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN FUNC_DEF ASSIGN VAR VAR IF VAR NUMBER RETURN FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def __init__(self):
self.res = -10000
def binary_search(self, arr, sum_search):
subarray = 0
sum1 = 0
for num in arr:
sum1 += num
if sum1 > sum_search:
subarray += 1
sum1 = num
return subarray + 1 <= self.K
def recursion(self, arr):
print(self.low, self.high)
if self.low == self.high:
self.res = self.low
return
sum_search = int((self.low + self.high) / 2) + 1
if self.binary_search(arr, sum_search):
self.high = sum_search - 1
self.recursion(arr)
else:
self.low = sum_search + 1
self.recursion(arr)
return
def splitArray(self, arr, n, K):
def fun(mid):
subarray = 0
curSum = 0
for i in arr:
curSum += i
if curSum > mid:
subarray += 1
curSum = i
return subarray + 1 <= K
l, r = max(arr), sum(arr)
res = r
while l <= r:
mid = l + r >> 1
if fun(mid):
res = mid
r = mid - 1
else:
l = mid + 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR RETURN BIN_OP VAR NUMBER VAR FUNC_DEF EXPR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR VAR RETURN ASSIGN VAR BIN_OP FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER NUMBER IF FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR RETURN BIN_OP VAR NUMBER VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
mi = max(arr)
ma = sum(arr)
while mi <= ma:
mid = (mi + ma) // 2
subarr = 0
su = 0
for i in range(N):
su += arr[i]
if su > mid:
subarr += 1
su = arr[i]
if subarr + 1 <= K:
ans = mid
ma = mid - 1
else:
mi = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF BIN_OP VAR NUMBER VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def isPossible(self, nums, mid, k):
subarr_count, subarr_sum = 1, 0
for i in range(len(nums)):
subarr_sum += nums[i]
if subarr_sum > mid:
subarr_count += 1
subarr_sum = nums[i]
if subarr_count <= k:
return True
else:
return False
def splitArray(self, nums, n, k):
if k > len(nums):
return -1
res = -1
low, high = max(nums), sum(nums)
while low <= high:
mid = low + (high - low) // 2
if self.isPossible(nums, mid, k):
res = mid
high = mid - 1
else:
low = mid + 1
return res | CLASS_DEF FUNC_DEF ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR FUNC_CALL VAR VAR RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
sum = 0
if N < K:
return -1
for i in range(N):
sum += arr[i]
start, end = 0, sum
result = 10**9
while start <= end:
mid = (start + end) // 2
if self.isPossible(arr, N, K, mid):
result = mid
end = mid - 1
else:
start = mid + 1
return result
def isPossible(self, arr, n, k, curr_min):
partsRequired = 1
curr_sum = 0
for i in range(n):
if arr[i] > curr_min:
return False
if curr_sum + arr[i] > curr_min:
partsRequired += 1
curr_sum = arr[i]
if partsRequired > k:
return False
else:
curr_sum += arr[i]
return True | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER IF VAR VAR RETURN NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR NUMBER VAR ASSIGN VAR BIN_OP NUMBER NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN NUMBER IF BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR RETURN NUMBER VAR VAR VAR RETURN NUMBER |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
low = max(arr)
high = int()
for i in arr:
high += i
if K > N:
return -1
while low <= high:
mid = (high - low) // 2 + low
cuts = 1
sum = 0
for ele in arr:
sum += ele
if sum > mid:
sum = ele
cuts += 1
if cuts > K:
low = mid + 1
else:
high = mid - 1
return high + 1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR VAR VAR IF VAR VAR RETURN NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP VAR VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN BIN_OP VAR NUMBER |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
s = min(arr) - 1
e = sum(arr)
while 1 < e - s:
m = (e + s) // 2
i = 0
j = 0
sub_sum = 0
success = True
while j < N:
if m < arr[j]:
success = False
break
if sub_sum + arr[j] <= m:
sub_sum += arr[j]
else:
sub_sum = arr[j]
i += 1
j += 1
if i == K:
success = False
break
if success:
e = m
else:
s = m
return e | CLASS_DEF FUNC_DEF ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR WHILE NUMBER BIN_OP VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR ASSIGN VAR NUMBER IF BIN_OP VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER VAR NUMBER IF VAR VAR ASSIGN VAR NUMBER IF VAR ASSIGN VAR VAR ASSIGN VAR VAR RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
left, right = max(arr), sum(arr)
while left < right:
mid = (left + right) // 2
curSum, count = 0, 0
for num in arr:
curSum += num
if curSum > mid:
curSum = num
count += 1
if count >= K:
left = mid + 1
else:
right = mid
return right | CLASS_DEF FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR NUMBER NUMBER FOR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
lo, hi = max(arr), sum(arr)
ans_candidate = lo
while lo <= hi:
potential_maximum = lo + (hi - lo) // 2
subarrays_count = 1
current_sum = 0
for a in arr:
current_sum += a
if current_sum > potential_maximum:
current_sum = a
subarrays_count += 1
if subarrays_count <= K:
ans_candidate = potential_maximum
hi = potential_maximum - 1
else:
lo = potential_maximum + 1
return ans_candidate | CLASS_DEF FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, n, k):
st = max(arr)
end = sum(arr)
cnt = 0
ans = end + 1
if k == 1:
return end
if k == n:
return st
while st <= end:
mid = (st + end) // 2
sm = 0
cnt = 0
for i in range(n):
sm += arr[i]
if sm == mid:
sm = 0
cnt += 1
elif sm > mid:
sm = arr[i]
cnt += 1
if i == n - 1:
cnt += 1
elif i == n - 1 and sm != 0:
cnt += 1
if cnt > k:
st = mid + 1
else:
if 1:
ans = min(ans, mid)
end = mid - 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER IF VAR NUMBER RETURN VAR IF VAR VAR RETURN VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR NUMBER VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR NUMBER IF VAR BIN_OP VAR NUMBER VAR NUMBER VAR NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR NUMBER IF NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def canSplit(n):
sub = 0
cur = 0
for i in arr:
cur += i
if cur > n:
sub += 1
cur = i
return sub + 1 <= K
l, r = arr[0], 0
for i in range(N):
l = max(l, arr[i])
r += arr[i]
res = r
while l <= r:
mid = l + (r - l) // 2
if canSplit(mid):
res = mid
r = mid - 1
else:
l = mid + 1
return res | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR RETURN BIN_OP VAR NUMBER VAR ASSIGN VAR VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def isvalid(self, max_val, arr, K):
co = 0
curr = 0
for i in arr:
if curr + i > max_val:
curr = i
co += 1
else:
curr += i
if curr <= max_val:
co += 1
return co <= K
def splitArray(self, arr, N, K):
low = max(arr)
high = sum(arr)
while low <= high:
mid = low + (high - low) // 2
if self.isvalid(mid, arr, K):
ans = mid
high = mid - 1
else:
low = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR NUMBER VAR VAR IF VAR VAR VAR NUMBER RETURN VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
start = max(arr)
end = 0
for i in arr:
end += i
mid = 0
ans = 0
while start <= end:
mid = (start + end) // 2
count = 0
m_sum = 0
for i in arr:
if i > mid:
return False
m_sum += i
if m_sum > mid:
count += 1
m_sum = i
count += 1
if count <= K:
ans = mid
end = mid - 1
else:
start = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF VAR VAR RETURN NUMBER VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def check(arr, N, K, mid):
cur_sum = 0
i = 0
while i < N:
if cur_sum + arr[i] <= mid:
cur_sum += arr[i]
elif cur_sum + arr[i] > mid and arr[i] <= mid and K > 1:
K -= 1
cur_sum = arr[i]
else:
return False
i += 1
return True
hi = sum(arr)
lo = 0
ans = 0
while lo <= hi:
mid = (lo + hi) // 2
if check(arr, N, K, mid):
ans = mid
hi = mid - 1
else:
lo = mid + 1
return ans | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR RETURN NUMBER VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def canSplit(largest):
subarray = 0
curSum = 0
for i in range(N):
curSum += arr[i]
if curSum > largest:
subarray += 1
curSum = arr[i]
return subarray + 1 <= K
left = max(arr)
right = sum(arr)
while left <= right:
mid = (left + right) // 2
if canSplit(mid):
ans = mid
right = mid - 1
else:
left = mid + 1
return ans | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR RETURN BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def ispossible(self, arr, curr, m):
csum = 0
stu = 1
for i in range(len(arr)):
if arr[i] > curr:
return False
if csum + arr[i] > curr:
stu += 1
csum = arr[i]
if stu > m:
return False
else:
csum += arr[i]
return True
def binarysearch(self, arr, m, l, r):
if l <= r:
mid = (l + r) // 2
if self.ispossible(arr, mid, m):
return self.binarysearch(arr, m, l, mid - 1)
else:
return self.binarysearch(arr, m, mid + 1, r)
return l
def splitArray(self, arr, N, K):
return self.binarysearch(arr, K, 0, sum(arr)) | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN NUMBER IF BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR RETURN NUMBER VAR VAR VAR RETURN NUMBER FUNC_DEF IF VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER RETURN FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR RETURN VAR FUNC_DEF RETURN FUNC_CALL VAR VAR VAR NUMBER FUNC_CALL VAR VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def isPossible(self, arr, N, K, mid):
count = 1
total_sum = 0
for i in range(N):
if total_sum + arr[i] <= mid:
total_sum += arr[i]
else:
count += 1
if count > K or arr[i] > mid:
return False
else:
total_sum = arr[i]
return True
def splitArray(self, arr, N, K):
start = 0
total = 0
for i in arr:
total += i
end = total
ans = -1
mid = start + (end - start) // 2
while start <= end:
if self.isPossible(arr, N, K, mid):
ans = mid
end = mid - 1
else:
start = mid + 1
mid = start + (end - start) // 2
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR VAR RETURN NUMBER ASSIGN VAR VAR VAR RETURN NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER WHILE VAR VAR IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | def isPossible(arr, mid, K):
n = 1
res = 0
for i in range(len(arr)):
if arr[i] > mid:
return False
if res + arr[i] > mid:
n += 1
res = arr[i]
if n > K:
return False
else:
res += arr[i]
return True
class Solution:
def splitArray(self, arr, N, K):
high = sum(arr)
low = 0
ans = 10000000000
while low <= high:
mid = (low + high) // 2
if isPossible(arr, mid, K):
ans = min(ans, mid)
high = mid - 1
else:
low = mid + 1
return ans | FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR VAR RETURN NUMBER IF BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR RETURN NUMBER VAR VAR VAR RETURN NUMBER CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def is_sum_poss(max_sum):
index = 0
sub_arr = 0
curr_sum = 0
while index < N:
if curr_sum + arr[index] > max_sum:
curr_sum = arr[index]
sub_arr += 1
else:
curr_sum += arr[index]
index += 1
return sub_arr + 1 if curr_sum != 0 else 0
max_sum = sum(arr)
l = max(arr)
h = max_sum
while l < h:
mid = l + (h - l) // 2
poss_sub_arr = is_sum_poss(mid)
if poss_sub_arr <= K:
h = mid
else:
l = mid + 1
return l | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF BIN_OP VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER VAR VAR VAR VAR NUMBER RETURN VAR NUMBER BIN_OP VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | def check(stack, k, target) -> bool:
n = len(arr)
j = n - 1
need = target
if k == n:
if target >= max(stack):
return True
else:
return False
for i in range(k):
if j < 0:
return True
while need > 0:
if stack[j] > target:
return False
if stack[j] > need:
break
need -= stack[j]
j -= 1
if j < 0:
break
need = target
if j >= 0:
return False
return True
def bin(arr, k, low, high):
mid = (low + high) // 2
if high == low:
return low
if check(arr, k, mid) == True:
return bin(arr, k, low, mid)
else:
return bin(arr, k, mid + 1, high)
class Solution:
def splitArray(self, arr, N, K):
return bin(arr, K, 1, sum(arr)) | FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR IF VAR VAR IF VAR FUNC_CALL VAR VAR RETURN NUMBER RETURN NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN NUMBER WHILE VAR NUMBER IF VAR VAR VAR RETURN NUMBER IF VAR VAR VAR VAR VAR VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR VAR IF VAR NUMBER RETURN NUMBER RETURN NUMBER VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR RETURN VAR IF FUNC_CALL VAR VAR VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR BIN_OP VAR NUMBER VAR CLASS_DEF FUNC_DEF RETURN FUNC_CALL VAR VAR VAR NUMBER FUNC_CALL VAR VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, n, k):
s = sum(arr)
low = s // k
high = s
mn = 10**9
while low <= high:
mx = 0
mid = (low + high) // 2
c = 1
sm = 0
for i in range(n):
if sm + arr[i] <= mid:
sm += arr[i]
else:
c += 1
mx = max(mx, sm)
sm = arr[i]
mx = max(mx, sm)
if c <= k:
mn = min(mn, mx)
high = mid - 1
else:
low = mid + 1
return mn | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP NUMBER NUMBER WHILE VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | def check(arr, k, n, mid):
val = 0
cnt = 0
for i in range(n):
val += arr[i]
if val > mid:
val = arr[i]
cnt += 1
if cnt == k and i < n:
return False
return True
class Solution:
def splitArray(self, arr, n, k):
l = 0
h = 0
for i in arr:
if l < i:
l = i
h += i
while l <= h:
mid = (l + h) // 2
if check(arr, k, n, mid):
h = mid - 1
else:
l = mid + 1
return l | FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR RETURN NUMBER RETURN NUMBER CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
def canSplit(maximum):
part = 1
curSum = 0
for n in arr:
if n > maximum:
return False
if curSum + n > maximum:
part += 1
curSum = n
else:
curSum += n
return part <= K
low = max(arr)
high = sum(arr)
if K == 1:
return high
if K == N:
return low
ans = high
while low <= high:
mid = low + high >> 1
if canSplit(mid):
ans = mid
high = mid - 1
else:
low = mid + 1
return ans | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF VAR VAR RETURN NUMBER IF BIN_OP VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER RETURN VAR IF VAR VAR RETURN VAR ASSIGN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
return my_answer(arr, N, K)
def my_answer(arr, N, K):
max_ans = sum(arr)
min_ans = max(arr)
while min_ans < max_ans:
mid_ans = (min_ans + max_ans) // 2
k_needed = 1
subarray_sum = 0
for val in arr:
subarray_sum += val
if subarray_sum > mid_ans:
k_needed += 1
subarray_sum = val
if k_needed <= K:
max_ans = mid_ans
else:
assert k_needed > K
min_ans = mid_ans + 1
assert min_ans == max_ans
return min_ans | CLASS_DEF FUNC_DEF RETURN FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER VAR VAR RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def check_possible(self, mid, arr, K):
curr_sum = 0
counter = K
buckets = [(0) for _ in range(K)]
for val in arr:
if counter <= 0:
return False
if val > mid:
return False
if curr_sum + val > mid:
curr_sum = val
counter -= 1
else:
curr_sum += val
if counter > 0:
return True
return False
def splitArray(self, arr, N, K):
sum_arr = 0
for val in arr:
sum_arr += val
left = 0
right = sum_arr
printing_counter = 100
while right - left > 1:
mid = int((right + left) / 2)
possible = self.check_possible(mid, arr, K)
if possible:
right = mid
else:
left = mid
if self.check_possible(left, arr, K):
return left
else:
return right | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR FOR VAR VAR IF VAR NUMBER RETURN NUMBER IF VAR VAR RETURN NUMBER IF BIN_OP VAR VAR VAR ASSIGN VAR VAR VAR NUMBER VAR VAR IF VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR NUMBER FOR VAR VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER WHILE BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR IF VAR ASSIGN VAR VAR ASSIGN VAR VAR IF FUNC_CALL VAR VAR VAR VAR RETURN VAR RETURN VAR |
Given an array arr[] of N elements and a number K. Split the given array into K subarrays such that the maximum subarray sum achievable out of K subarrays formed is minimum possible. Find that possible subarray sum.
Example 1:
Input:
N = 4, K = 3
arr[] = {1, 2, 3, 4}
Output: 4
Explanation:
Optimal Split is {1, 2}, {3}, {4}.
Maximum sum of all subarrays is 4,
which is minimum possible for 3 splits.
Example 2:
Input:
N = 3, K = 2
A[] = {1, 1, 2}
Output:
2
Explanation:
Splitting the array as {1,1} and {2} is optimal.
This results in a maximum sum subarray of 2.
Your Task:
The task is to complete the function splitArray() which returns the maximum sum subarray after splitting the array into K subarrays such that maximum sum subarray is minimum possible.
Constraints:
1 ≤ N ≤ 10^{5}
1 ≤ K ≤ N
1 ≤ arr[i] ≤ 10^{4}
Expected Time Complexity: O(N*log(sum(arr))).
Expected Auxiliary Space: O(1). | class Solution:
def splitArray(self, arr, N, K):
l = 0
h = 0
for i in arr:
l = max(l, i)
h += i
def ispossible(arr, maxsum, k):
cnt = 0
currsum = 0
for i in arr:
if currsum + i > maxsum:
cnt += 1
currsum = i
else:
currsum += i
if currsum <= maxsum:
cnt += 1
return cnt <= k
while l <= h:
mid = l + (h - l) // 2
if ispossible(arr, mid, K):
ans = mid
h = mid - 1
else:
l = mid + 1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR IF BIN_OP VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR IF VAR VAR VAR NUMBER RETURN VAR VAR WHILE VAR VAR ASSIGN VAR BIN_OP VAR BIN_OP BIN_OP VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER RETURN VAR |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | import sys
from sys import stdin
def bitadd(a, w, bit):
x = a
while x <= len(bit) - 1:
bit[x] += w
x += x & -1 * x
def bitsum(a, bit):
ret = 0
x = a
while x > 0:
ret += bit[x]
x -= x & -1 * x
return ret
tt = int(stdin.readline())
ANS = []
for loop in range(tt):
N = n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
dic = {}
lis = []
for i in range(n):
if a[i] not in dic:
dic[a[i]] = 0
lis.append(a[i])
lis.sort()
for i in range(len(lis)):
dic[lis[i]] = i + 1
if len(dic) != n:
ANS.append("YES")
continue
BIT = [0] * (len(lis) + 2)
ans = 0
for i in range(N):
ans += i - bitsum(dic[a[i]], BIT)
bitadd(dic[a[i]], 1, BIT)
if ans % 2 == 0:
ANS.append("YES")
else:
ANS.append("NO")
print("\n".join(ANS)) | IMPORT FUNC_DEF ASSIGN VAR VAR WHILE VAR BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR BIN_OP VAR BIN_OP NUMBER VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR NUMBER VAR VAR VAR VAR BIN_OP VAR BIN_OP NUMBER VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR DICT ASSIGN VAR LIST FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP LIST NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER VAR IF BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_CALL STRING VAR |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | for _ in range(int(input())):
n, a = int(input()), list(map(int, input().split()))
if len(set(a)) < n:
print("YES")
continue
sorted_a = sorted(a)
num2i = {num: i for i, num in enumerate(sorted_a)}
vis = [0] * n
ans = 0
for i in range(n):
if vis[i]:
continue
size, cur = 0, i
while not vis[cur]:
vis[cur] = 1
size, cur = size + 1, num2i[a[cur]]
ans += size % 2 == 0
print("YES") if ans == 0 or ans % 2 == 0 else print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR NUMBER VAR WHILE VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER VAR VAR VAR VAR BIN_OP VAR NUMBER NUMBER EXPR VAR NUMBER BIN_OP VAR NUMBER NUMBER FUNC_CALL VAR STRING FUNC_CALL VAR STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | def count_inversions(a):
res = 0
counts = [0] * (len(a) + 1)
rank = {v: (i + 1) for i, v in enumerate(sorted(a))}
for x in reversed(a):
i = rank[x] - 1
while i:
res += counts[i]
i -= i & -i
i = rank[x]
while i <= len(a):
counts[i] += 1
i += i & -i
return res
T = int(input())
for testcase in range(1, T + 1):
n = int(input())
a = list(map(int, input().split()))
b = a.copy()
b.sort()
found = False
for i in range(n - 1):
if b[i] == b[i + 1]:
found = True
break
if found:
print("YES")
elif count_inversions(a) % 2 == 0:
print("YES")
else:
print("NO") | FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR NUMBER WHILE VAR VAR VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR WHILE VAR FUNC_CALL VAR VAR VAR VAR NUMBER VAR BIN_OP VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF VAR EXPR FUNC_CALL VAR STRING IF BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | import sys
int1 = lambda x: int(x) - 1
pDB = lambda *x: print(*x, end="\n", file=sys.stderr)
p2D = lambda x: print(*x, sep="\n", end="\n\n", file=sys.stderr)
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number):
return [LI() for _ in range(rows_number)]
def LI1():
return list(map(int1, sys.stdin.readline().split()))
def LLI1(rows_number):
return [LI1() for _ in range(rows_number)]
def SI():
return sys.stdin.readline().rstrip()
inf = 4294967295
md = 998244353
def solve():
n = II()
aa = LI1()
if len(set(aa)) < n:
return True
fin = [0] * n
even = 0
for i in range(n):
if fin[i]:
continue
s = 1
while fin[i] == 0:
fin[i] = 1
s ^= 1
i = aa[i]
even += s
return even & 1 == 0
for testcase in range(II()):
print("YES" if solve() else "NO") | IMPORT ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR STRING VAR ASSIGN VAR FUNC_CALL VAR VAR STRING STRING VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF RETURN FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_CALL VAR VAR FUNC_DEF RETURN FUNC_CALL FUNC_CALL VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR VAR RETURN NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR NUMBER WHILE VAR VAR NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR VAR RETURN BIN_OP VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR STRING STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)
def f(A, L: int, R: int) -> int:
if R - L <= 1:
return 0
m = (L + R) // 2
r = f(A, L, m) + f(A, m, R)
tmp = []
i = L
j = m
while i < m or j < R:
if i < m and (j == R or A[i] <= A[j]):
tmp.append(A[i])
i += 1
else:
tmp.append(A[j])
r += m - i
j += 1
assert len(tmp) == R - L
A[L:R] = tmp
return r
for _ in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
inv = f(A, 0, N)
if len(set(A)) != N:
print("YES")
continue
print("YES" if inv % 2 == 0 else "NO") | IMPORT ASSIGN VAR VAR EXPR FUNC_CALL VAR BIN_OP NUMBER NUMBER FUNC_DEF VAR VAR IF BIN_OP VAR VAR NUMBER RETURN NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR VAR ASSIGN VAR VAR WHILE VAR VAR VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR VAR VAR NUMBER FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER STRING STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | import sys
input = sys.stdin.readline
def merge(L1, L2):
inv = 0
pt1 = 0
pt2 = 0
res = []
for i in range(len(L1) + len(L2)):
if len(L1) == pt1:
res.append(L2[pt2])
pt2 += 1
elif len(L2) == pt2:
res.append(L1[pt1])
pt1 += 1
elif L1[pt1] > L2[pt2]:
res.append(L2[pt2])
inv += len(L1) - pt1
pt2 += 1
else:
res.append(L1[pt1])
pt1 += 1
return res, inv
def mergeSort(L1):
if len(L1) < 2:
return L1, 0
left = L1[: len(L1) // 2]
right = L1[len(L1) // 2 :]
left, inv1 = mergeSort(left)
right, inv2 = mergeSort(right)
res, inv = merge(left, right)
return res, inv + inv1 + inv2
for _ in " " * int(input()):
n = int(input())
L = list(map(int, input().split()))
res, inv = mergeSort(L)
double = False
for i in range(n - 1):
if res[i] == res[i + 1]:
double = True
break
if double or inv % 2 == 0:
print("YES")
else:
print("NO") | IMPORT ASSIGN VAR VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR LIST FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR BIN_OP FUNC_CALL VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR NUMBER RETURN VAR VAR FUNC_DEF IF FUNC_CALL VAR VAR NUMBER RETURN VAR NUMBER ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR RETURN VAR BIN_OP BIN_OP VAR VAR VAR FOR VAR BIN_OP STRING FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER IF VAR BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | class BIT:
def __init__(self, L):
self.N = len(L)
self.bit = [0] * self.N
for i, l in enumerate(L):
self.add(i, l)
self.N0 = 1
while self.N0 * 2 <= self.N:
self.N0 *= 2
def add(self, a, w):
x = a + 1
for i in range(1000):
self.bit[x - 1] += w
x += x & -x
if x > self.N:
break
def sum(self, a):
x = a + 1
ret = 0
for i in range(1000):
ret += self.bit[x - 1]
x -= x & -x
if x <= 0:
break
return ret
def lower_bound(self, w):
if w <= 0:
return 0
x = 0
k = self.N0
while k > 0:
if x + k <= self.N:
if self.bit[x + k - 1] < w:
w -= self.bit[x + k - 1]
x += k
k //= 2
return x + 1
def solve():
N = int(input())
A = list(map(int, input().split()))
if len(set(A)) < len(A):
print("YES")
return
bit = BIT([0] * N)
A = [(a, i) for i, a in enumerate(A)]
A.sort(key=lambda x: x[0], reverse=True)
tento = 0
buf = []
prev = A[0][0]
for a, i in A:
if prev != a:
for b in buf:
bit.add(b, 1)
buf = []
prev = a
tento += bit.sum(i)
buf.append(i)
if tento % 2 == 0:
print("YES")
else:
print("NO")
T = int(input())
for i in range(T):
solve() | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER WHILE BIN_OP VAR NUMBER VAR VAR NUMBER FUNC_DEF ASSIGN VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR BIN_OP VAR VAR IF VAR VAR FUNC_DEF ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR VAR IF VAR NUMBER RETURN VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR WHILE VAR NUMBER IF BIN_OP VAR VAR VAR IF VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR VAR NUMBER RETURN BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR STRING RETURN ASSIGN VAR FUNC_CALL VAR BIN_OP LIST NUMBER VAR ASSIGN VAR VAR VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR LIST ASSIGN VAR VAR NUMBER NUMBER FOR VAR VAR VAR IF VAR VAR FOR VAR VAR EXPR FUNC_CALL VAR VAR NUMBER ASSIGN VAR LIST ASSIGN VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
if n == 1:
print("YES")
continue
h = n != len(set(a))
b = sorted(a)
d = dict()
for i, x in enumerate(a):
d[x] = d.get(x, set())
d[x].add(i)
i = n - 1
while i > 1:
r = a[i]
t = b[i]
if r != t:
ti = 0
for tix in d[t]:
ti = tix
break
z = 0
if ti == z:
z = 1
az = a[z]
a[i] = t
d[t].remove(ti)
a[ti] = a[z]
d[az].remove(z)
d[az].add(ti)
a[z] = r
d[r].remove(i)
d[r].add(z)
i -= 1
if a[0] == b[0] and a[1] == b[1]:
print("YES")
elif h:
print("YES")
else:
print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR ASSIGN VAR NUMBER FOR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER IF VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR STRING IF VAR EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
if len(set(a)) != len(a):
print("YES")
elif n == 1:
print("YES")
else:
curridxs = {}
for i, x in enumerate(a):
curridxs[x] = i
sorteda = sorted(a)
for i in range(n - 2):
if sorteda[i] != a[i]:
firsti = i
secondi = curridxs[sorteda[i]]
thirdi = i + 1 if secondi != i + 1 else n - 1
firstc = a[firsti]
secondc = a[secondi]
thirdc = a[thirdi]
tempi = firsti
a[firsti] = secondc
a[secondi] = thirdc
a[thirdi] = firstc
curridxs[firstc] = thirdi
curridxs[secondc] = firsti
curridxs[thirdc] = secondi
if a[n - 2] < a[n - 1]:
print("YES")
else:
print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR STRING IF VAR NUMBER EXPR FUNC_CALL VAR STRING ASSIGN VAR DICT FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | for t in range(int(input())):
n = int(input())
ns = list(map(int, input().split()))
ns = [(i - 1) for i in ns]
nss = [i for i in ns]
nss.sort()
f = True
for i in range(n):
if nss[i] != i:
f = False
print("YES")
break
if f:
total = 0
dic = dict()
for i in range(n):
dic[ns[i]] = i
for i in range(n - 2):
if dic[i] == i:
continue
ix, jx, kx = dic[i], i, i + 1
if ix == i + 1:
kx = i + 2
ns[ix], ns[jx], ns[kx] = ns[kx], ns[ix], ns[jx]
dic[ns[ix]], dic[ns[jx]], dic[ns[kx]] = ix, jx, kx
if ns[n - 1] == n - 1:
print("YES")
else:
print("NO") | FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR NUMBER EXPR FUNC_CALL VAR STRING IF VAR ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR BIN_OP VAR NUMBER IF VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR IF VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER EXPR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR STRING |
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array. | import sys
inpu = sys.stdin.readline
prin = sys.stdout.write
t = int(inpu())
for _ in range(t):
n = int(inpu())
a = list(map(int, inpu().split()))
if len(set(a)) < n:
print("yes")
continue
inds = {}
b = sorted(a)
for i in range(n):
inds[a[i]] = i
swaps = 0
for j in range(n):
if a[j] != b[j]:
swaps += 1
loc = inds[b[j]]
inds[a[j]] = loc
inds[a[loc]] = j
a[j], a[loc] = a[loc], a[j]
print("yes" if swaps % 2 == 0 else "no") | IMPORT ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_CALL FUNC_CALL VAR IF FUNC_CALL VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR STRING ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER STRING STRING |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
def checkCovered(self, A, B):
if B[0] <= A[0] and A[1] <= B[1]:
return True
else:
return False
res = len(intervals)
for i, interval in enumerate(intervals):
tmp = intervals[:i] + intervals[i + 1 :]
for each in tmp:
if checkCovered(self, interval, each):
res -= 1
break
return res | CLASS_DEF FUNC_DEF VAR VAR VAR FUNC_DEF IF VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER RETURN NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR BIN_OP VAR NUMBER FOR VAR VAR IF FUNC_CALL VAR VAR VAR VAR VAR NUMBER RETURN VAR VAR |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))
endingval = 0
res = 0
for _, end in intervals:
if endingval < end:
endingval = end
res += 1
return res | CLASS_DEF FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR NUMBER RETURN VAR VAR |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda tup: tup[1] - tup[0], reverse=True)
covered = set()
for i in range(len(intervals)):
s, e = intervals[i]
for j in range(i + 1, len(intervals)):
s2, e2 = intervals[j]
if s <= s2 and e2 <= e:
covered.add(j)
return len(intervals) - len(covered) | CLASS_DEF FUNC_DEF VAR VAR VAR EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
cov = 0
def covered(first, second):
return first[0] <= second[0] and second[1] <= first[1]
for pos, inter1 in enumerate(intervals):
for checkpos, inter2 in enumerate(intervals):
if pos != checkpos and covered(inter2, inter1):
cov += 1
break
return len(intervals) - cov | CLASS_DEF FUNC_DEF VAR VAR VAR ASSIGN VAR NUMBER FUNC_DEF RETURN VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER FOR VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR IF VAR VAR FUNC_CALL VAR VAR VAR VAR NUMBER RETURN BIN_OP FUNC_CALL VAR VAR VAR VAR |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
L = len(intervals)
discard = set()
for i in range(L):
x, y = intervals[i]
for j in range(i + 1, L):
a, b = intervals[j]
if a <= x and b >= y:
discard.add((x, y))
elif x <= a and y >= b:
discard.add((a, b))
return L - len(discard) | CLASS_DEF FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN BIN_OP VAR FUNC_CALL VAR VAR VAR |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
first = [x[0] for x in intervals]
indices = [i[0] for i in sorted(enumerate(first), key=lambda x: x[1])]
sorted_intervals = [intervals[i] for i in indices]
remove = []
flag = True
while flag == True:
flag = False
for i in range(len(sorted_intervals) - 1):
c, d = sorted_intervals[i][0], sorted_intervals[i][1]
a, b = sorted_intervals[i + 1][0], sorted_intervals[i + 1][1]
if c <= a and b <= d:
remove.append([a, b])
flag = True
elif a <= c and d <= b:
remove.append([c, d])
flag = True
sorted_intervals = [x for x in sorted_intervals if x not in remove]
return len(sorted_intervals) | CLASS_DEF FUNC_DEF VAR VAR VAR ASSIGN VAR VAR NUMBER VAR VAR ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR ASSIGN VAR LIST ASSIGN VAR NUMBER WHILE VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR VAR EXPR FUNC_CALL VAR LIST VAR VAR ASSIGN VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR |
Given a list of intervals, remove all intervals that are covered by another interval in the list.
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
After doing so, return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Example 3:
Input: intervals = [[0,10],[5,12]]
Output: 2
Example 4:
Input: intervals = [[3,10],[4,10],[5,11]]
Output: 2
Example 5:
Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
Constraints:
1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= intervals[i][0] < intervals[i][1] <= 10^5
All the intervals are unique. | class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
i = set(map(tuple, intervals))
l = set()
for a in i:
for b in i - {a} - l:
if a == b:
continue
if covered(a, b):
l.add(a)
break
return len(i) - len(l)
def covered(a, b):
return b[0] <= a[0] and a[1] <= b[1] | CLASS_DEF FUNC_DEF VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR FOR VAR BIN_OP BIN_OP VAR VAR VAR IF VAR VAR IF FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR VAR FUNC_DEF RETURN VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.