description stringlengths 171 4k | code stringlengths 94 3.98k | normalized_code stringlengths 57 4.99k |
|---|---|---|
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | t = int(input())
m = 7 + 10**9
den = pow(25, 1000000005, 1000000007)
for i in range(0, t):
n = int(input())
t = (n + 1) // 2
s = 52 * ((pow(26, t, 1000000007) - 1) % m) % m
s = s * den % m
if n % 2 == 0:
print(str(s))
else:
print(str((s - pow(26, t, 1000000007)) % 1000000007)) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP NUMBER BIN_OP NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER BIN_OP BIN_OP FUNC_CALL VAR NUMBER VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR IF BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR BIN_OP BIN_OP VAR FUNC_CALL VAR NUMBER VAR NUMBER NUMBER |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | MOD = 1000000007
def mult(A, B):
R = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
result = 0
for k in range(len(B)):
result += A[i][k] * B[k][j] % MOD
result %= MOD
row.append(result)
R.append(row)
return R
def power(A, p):
if p == 1:
return A
Anb2 = power(A, int(p / 2))
R = mult(Anb2, Anb2)
if p & 1:
return mult(R, A)
else:
return R
def powerNum(A, p):
if p == 1:
return A
Anb2 = powerNum(A, int(p / 2))
R = Anb2 * Anb2 % MOD
if p & 1:
return R * A % MOD
else:
return R
def powerSum(n, p):
A = [[n, 1], [0, 1]]
M0 = [[0], [n]]
Ap = power(A, p)
R = mult(Ap, M0)
return R[0][0]
def solution():
n = int(input())
if n == 1:
print(26)
return
sum = powerSum(26, int(n / 2)) * 2 % MOD
if n & 1:
sum += powerNum(26, int((n + 1) / 2))
sum %= MOD
print(sum)
T = int(input())
while T > 0:
T = T - 1
solution() | ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR LIST FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR LIST FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF IF VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF BIN_OP VAR NUMBER RETURN FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR IF BIN_OP VAR NUMBER RETURN BIN_OP BIN_OP VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR LIST LIST VAR NUMBER LIST NUMBER NUMBER ASSIGN VAR LIST LIST NUMBER LIST VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR IF VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR NUMBER FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER VAR IF BIN_OP VAR NUMBER VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR WHILE VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | def main():
modulo = 1000000007
for T in range(int(input())):
N = int(input())
t = N // 2
ans = 560000006 * (pow(26, t, modulo) - 1) % modulo
if N % 2:
ans = (ans + pow(26, t + 1, modulo)) % modulo
print(ans)
main() | FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER BIN_OP FUNC_CALL VAR NUMBER VAR VAR NUMBER VAR IF BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | MOD = 1000000007
def power(a, b):
if b == 0:
return 1
else:
temp = power(a, b // 2)
if b % 2 == 0:
return temp * temp % MOD
else:
return temp * temp * a % MOD
def InverseEuler(t):
return power(t, MOD - 2)
def aml(n):
p = n // 2
temp = 52 * (power(26, p) + MOD - 1) * InverseEuler(25) % MOD
return temp
t = int(input())
while t > 0:
t = t - 1
n = int(input())
if n % 2 == 0:
print(aml(n))
else:
l = (n + 1) // 2
q = (power(26, l) + aml(n)) % MOD
print(q) | ASSIGN VAR NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN BIN_OP BIN_OP VAR VAR VAR RETURN BIN_OP BIN_OP BIN_OP VAR VAR VAR VAR FUNC_DEF RETURN FUNC_CALL VAR VAR BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP NUMBER BIN_OP BIN_OP FUNC_CALL VAR NUMBER VAR VAR NUMBER FUNC_CALL VAR NUMBER VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR WHILE VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR IF BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR NUMBER VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | mod, i = 1000000007, 280000002
for _ in range(int(input())):
n = int(input())
t = (
2 * 26 * (pow(26, n // 2, mod) - 1) * i % mod
+ (n & 1) * pow(26, (n + 1) // 2, mod)
) % mod
print(t) | ASSIGN VAR VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP BIN_OP BIN_OP BIN_OP NUMBER NUMBER BIN_OP FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER VAR VAR BIN_OP BIN_OP VAR NUMBER FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR EXPR FUNC_CALL VAR VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | inv = 280000002
mod = 1000000007
def solve():
n = int(input())
if n % 2 == 0:
print(2 * ((pow(26, n // 2 + 1, mod) - 1) * inv - 1) % mod)
else:
print(
(2 * ((pow(26, n // 2 + 2, mod) - 1) * inv - 1) - pow(26, n // 2 + 1, mod))
% mod
)
for i in range(int(input())):
solve() | ASSIGN VAR NUMBER ASSIGN VAR NUMBER FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR IF BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR BIN_OP BIN_OP NUMBER BIN_OP BIN_OP BIN_OP FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER VAR NUMBER VAR NUMBER VAR EXPR FUNC_CALL VAR BIN_OP BIN_OP BIN_OP NUMBER BIN_OP BIN_OP BIN_OP FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER VAR NUMBER VAR NUMBER FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | mod = 10**9 + 7
def f(n):
k = n + 1 >> 1
ans = 26 * (pow(26, k, mod) - 1) * pow(25, mod - 2, mod) * 2
if n % 2:
ans -= pow(26, k, mod)
ans %= mod
return ans
for _ in range(int(eval(input()))):
n = int(eval(input()))
print(f(n)) | ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP NUMBER BIN_OP FUNC_CALL VAR NUMBER VAR VAR NUMBER FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER VAR FUNC_CALL VAR NUMBER VAR VAR VAR VAR RETURN VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | def get_power(a, N, m, D):
if N == 0:
return 1
elif N == 1:
return a
elif N in D:
return D[N]
else:
D[N] = get_power(a, N // 2, m, D) % m * (get_power(a, N - N // 2, m, D) % m) % m
return D[N]
T = int(input())
ans = []
m = 10**9 + 7
for _ in range(T):
N = int(input())
if N % 2 == 0:
num = 52 % m * ((get_power(26, N // 2, m, {}) - 1) % m) % m
deno = get_power(25, m - 2, m, {})
t = num * deno % m
else:
N += 1
num = 52 % m * ((get_power(26, N // 2, m, {}) - 1) % m) % m
deno = get_power(25, m - 2, m, {})
t = (num * deno % m - get_power(26, N // 2, m, {})) % m
ans.append(t)
for i in ans:
print(i) | FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER RETURN VAR IF VAR VAR RETURN VAR VAR ASSIGN VAR VAR BIN_OP BIN_OP BIN_OP FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR VAR VAR BIN_OP FUNC_CALL VAR VAR BIN_OP VAR BIN_OP VAR NUMBER VAR VAR VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR LIST ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR IF BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP NUMBER VAR BIN_OP BIN_OP FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR DICT NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR DICT ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP NUMBER VAR BIN_OP BIN_OP FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR DICT NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR DICT ASSIGN VAR BIN_OP BIN_OP BIN_OP BIN_OP VAR VAR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR DICT VAR EXPR FUNC_CALL VAR VAR FOR VAR VAR EXPR FUNC_CALL VAR VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | import sys
m = 1000000007
mi26 = pow(25, m - 2, m)
sys.stdin.readline()
for line in sys.stdin.read().splitlines(0):
n = int(line)
ans = 1
if n & 1:
k = n // 2
ans = (
2 * (26 * ((pow(26, k, m) - 1) % m) * mi26) % m % m
+ pow(26, (n + 1) // 2, m)
) % m
else:
k = (n + 1) // 2
ans = 2 * (26 * ((pow(26, k, m) - 1) % m) * mi26) % m % m
print(ans) | IMPORT ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR EXPR FUNC_CALL VAR FOR VAR FUNC_CALL FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER IF BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP BIN_OP BIN_OP NUMBER BIN_OP BIN_OP NUMBER BIN_OP BIN_OP FUNC_CALL VAR NUMBER VAR VAR NUMBER VAR VAR VAR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP BIN_OP NUMBER BIN_OP BIN_OP NUMBER BIN_OP BIN_OP FUNC_CALL VAR NUMBER VAR VAR NUMBER VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR |
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish.
For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar").
For example:
- For N = 1, we have 26 different palindromes of length not exceeding N:
"a", "b", ..., "z".
- For N = 2 we have 52 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz".
- For N = 3 we have 728 different palindromes of length not exceeding N:
"a", "b", ..., "z",
"aa", "bb", ..., "zz",
"aaa", "aba", ..., "aza",
"bab", "bbb", ..., "bzb",
...,
"zaz", "zbz", ..., "zzz".
Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :)
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer N.
-----Output-----
For each test case, output a single line containing the answer for the corresponding test case.
-----Constrains-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 109
-----Example-----
Input:
5
1
2
3
4
100
Output:
26
52
728
1404
508533804
-----Explanation-----
The first three examples are explained in the problem statement above. | "__author__" == "deepak Singh Mehta(learning to code)) "
mod = 1000000007
def pow(n):
if n == 0:
return 1
if n % 2 == 1:
return 26 * pow(n - 1) % mod
tmp = pow(n // 2)
return tmp * tmp % mod
tests = int(input())
for _ in range(tests):
n = int(input())
curr = 26 * (pow(n // 2) - 1)
while curr % 25 != 0:
curr += mod
curr //= 25
curr *= 2
if n % 2 == 1:
curr += pow(n // 2 + 1)
print(curr % mod) | EXPR STRING STRING ASSIGN VAR NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER IF BIN_OP VAR NUMBER NUMBER RETURN BIN_OP BIN_OP NUMBER FUNC_CALL VAR BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER RETURN BIN_OP BIN_OP VAR 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 BIN_OP NUMBER BIN_OP FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER WHILE BIN_OP VAR NUMBER NUMBER VAR VAR VAR NUMBER VAR NUMBER IF BIN_OP VAR NUMBER NUMBER VAR FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify(ind):
global curr_size
par = ind
if 2 * ind + 1 < curr_size and heap[2 * ind + 1] < heap[par]:
par = 2 * ind + 1
if 2 * ind + 2 < curr_size and heap[2 * ind + 2] < heap[par]:
par = 2 * ind + 2
if par != ind:
heap[par], heap[ind] = heap[ind], heap[par]
heapify(par)
return
def insertKey(x):
global curr_size
curr_size += 1
heap[curr_size - 1] = x
i = curr_size - 1
while i > 0:
if heap[(i - 1) // 2] <= heap[i]:
break
heap[i], heap[(i - 1) // 2] = heap[(i - 1) // 2], heap[i]
i = (i - 1) // 2
def deleteKey(i):
global curr_size
if i < curr_size:
heap[i] = -999999999
ind = i
while ind > 0:
if heap[(ind - 1) // 2] <= heap[ind]:
break
heap[ind], heap[(ind - 1) // 2] = heap[(ind - 1) // 2], heap[ind]
ind = (ind - 1) // 2
extractMin()
def extractMin():
global curr_size
if curr_size == 0:
return -1
if curr_size == 1:
curr_size -= 1
return heap[curr_size]
ans = heap[0]
i = 0
if i < curr_size:
heap[i], heap[curr_size - 1] = heap[curr_size - 1], heap[i]
curr_size -= 1
heapify(i)
return ans | FUNC_DEF ASSIGN VAR VAR IF BIN_OP BIN_OP NUMBER VAR NUMBER VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER IF BIN_OP BIN_OP NUMBER VAR NUMBER VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN FUNC_DEF VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER IF VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF IF VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR WHILE VAR NUMBER IF VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER VAR NUMBER RETURN VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify(i):
global heap, curr_size
target = i
left = 2 * i + 1
right = 2 * i + 2
if left < curr_size and heap[left] < heap[target]:
target = left
if right < curr_size and heap[right] < heap[target]:
target = right
if target != i:
heap[i], heap[target] = heap[target], heap[i]
heapify(target)
def heapify2(i):
global heap
parent = (i - 1) // 2
while parent >= 0 and heap[parent] > heap[i]:
heap[parent], heap[i] = heap[i], heap[parent]
i, parent = parent, (parent - 1) // 2
def insertKey(x):
global heap, curr_size
heap[curr_size] = x
curr_size += 1
heapify2(curr_size - 1)
def deleteKey(i):
global heap, curr_size
if i >= curr_size:
return -1
heap[i] = float("-inf")
heapify2(i)
extractMin()
def extractMin():
global heap, curr_size
if curr_size == 0:
return -1
heap[0], heap[curr_size - 1] = heap[curr_size - 1], heap[0]
r = heap[curr_size - 1]
curr_size -= 1
heapify(0)
return r | FUNC_DEF ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def left(pos):
return 2 * pos + 1
def right(pos):
return 2 * pos + 2
def parent(pos):
return (pos - 1) // 2
def isleaf(pos):
if left(pos) > curr_size - 1:
return True
return False
def shiftdown(pos):
if not isleaf(pos):
smallest = pos
if heap[smallest] > heap[left(pos)]:
smallest = left(pos)
if heap[smallest] > heap[right(pos)]:
smallest = right(pos)
if smallest != pos:
heap[pos], heap[smallest] = heap[smallest], heap[pos]
shiftdown(smallest)
def shiftup(pos):
if pos > 0:
if heap[pos] < heap[parent(pos)]:
heap[pos], heap[parent(pos)] = heap[parent(pos)], heap[pos]
shiftup(parent(pos))
def decreaseKey(pos, val):
global heap
if val > heap[pos]:
return False
heap[pos] = val
shiftup(pos)
return True
def insertKey(x):
global curr_size, heap
if curr_size > 100:
return False
heap[curr_size] = x
curr_size += 1
shiftup(curr_size - 1)
def deleteKey(i):
global curr_size
if i >= curr_size:
return -1
decreaseKey(i, float("-inf"))
extractMin()
def extractMin():
global curr_size, heap
if curr_size == 0:
return -1
top = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
shiftdown(0)
return top | FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF IF FUNC_CALL VAR VAR ASSIGN VAR VAR IF VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NUMBER IF VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR VAR VAR RETURN NUMBER ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR RETURN NUMBER EXPR FUNC_CALL VAR VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def left(pos):
return 2 * pos + 1
def right(pos):
return 2 * pos + 2
def parent(pos):
return (pos - 1) // 2
def swap(pos1, pos2):
global heap
heap[pos1], heap[pos2] = heap[pos2], heap[pos1]
def isLeaf(pos):
if left(pos) > curr_size - 1:
return True
return False
def heapify(i):
global curr_size, heap
smallest = i
l, r = 2 * i + 1, 2 * i + 2
if l < curr_size and heap[smallest] > heap[l]:
smallest = l
if r < curr_size and heap[smallest] > heap[r]:
smallest = r
if smallest != i:
heap[smallest], heap[i] = heap[i], heap[smallest]
heapify(smallest)
def heapify2(i):
global curr_size, heap
parent = (i - 1) // 2
while parent >= 0 and heap[parent] > heap[i]:
heap[parent], heap[i] = heap[i], heap[parent]
i, parent = parent, (parent - 1) // 2
def decreaseKey(pos, val):
global heap
if val > heap[pos]:
return False
heap[pos] = val
heapify2(pos)
return True
def insertKey(x):
global curr_size, heap
if curr_size > 100:
return False
heap[curr_size] = x
curr_size += 1
heapify2(curr_size - 1)
def deleteKey(i):
global heap, curr_size
if i >= curr_size:
return -1
heap[i] = float("-inf")
heapify2(i)
extractMin()
def extractMin():
global heap, curr_size
if curr_size == 0:
return -1
top_ele = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
heapify(0)
return top_ele | FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR FUNC_DEF IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER RETURN NUMBER RETURN NUMBER FUNC_DEF ASSIGN VAR VAR ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF IF VAR VAR VAR RETURN NUMBER ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def siftUp(i):
parent = (i - 1) // 2
while i != 0 and heap[parent] > heap[i]:
heap[parent], heap[i] = heap[i], heap[parent]
i = parent
parent = (i - 1) // 2
def siftDown(i):
left = i * 2 + 1
right = i * 2 + 2
while (
left < curr_size
and heap[left] < heap[i]
or right < curr_size
and heap[right] < heap[i]
):
smallest = left if right >= curr_size or heap[left] <= heap[right] else right
heap[smallest], heap[i] = heap[i], heap[smallest]
i = smallest
left = i * 2 + 1
right = i * 2 + 2
def heapify():
for i in range(curr_size - 1, -1, -1):
siftDown(i)
def insertKey(x):
global curr_size
heap[curr_size] = x
curr_size += 1
siftUp(curr_size - 1)
def deleteKey(i):
global curr_size
if i >= curr_size:
return
heap[i], heap[curr_size - 1] = heap[curr_size - 1], heap[i]
heap[curr_size - 1] = 0
curr_size -= 1
heapify()
def extractMin():
global curr_size
if curr_size == 0:
return -1
minVal = heap[0]
heap[0], heap[curr_size - 1] = heap[curr_size - 1], heap[0]
heap[curr_size - 1] = 0
curr_size -= 1
siftDown(0)
return minVal | FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR RETURN ASSIGN VAR VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR VAR ASSIGN VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def getParent(x):
return (x - 1) // 2
def leftChild(x):
return 2 * x + 1 if 2 * x + 1 < curr_size else -1
def rightChild(x):
return 2 * x + 2 if 2 * x + 2 < curr_size else -1
def heapify():
curr_ind = curr_size - 1
while getParent(curr_ind) != -1 and heap[getParent(curr_ind)] > heap[curr_ind]:
heap[curr_ind], heap[getParent(curr_ind)] = (
heap[getParent(curr_ind)],
heap[curr_ind],
)
curr_ind = getParent(curr_ind)
return
def heapifyDown(x):
if x >= curr_size:
return
if getParent(x) != -1 and heap[x] < heap[getParent(x)]:
heap[x], heap[getParent(x)] = heap[getParent(x)], heap[x]
heapifyDown(getParent(x))
if leftChild(x) == -1 or leftChild(x) != -1 and heap[x] < heap[leftChild(x)]:
if rightChild(x) == -1 or rightChild(x) != -1 and heap[x] < heap[rightChild(x)]:
return
if rightChild(x) == -1:
heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x]
heapifyDown(leftChild(x))
elif leftChild(x) == -1:
heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x]
heapifyDown(rightChild(x))
elif heap[rightChild(x)] < heap[leftChild(x)]:
heap[x], heap[rightChild(x)] = heap[rightChild(x)], heap[x]
heapifyDown(rightChild(x))
else:
heap[x], heap[leftChild(x)] = heap[leftChild(x)], heap[x]
heapifyDown(leftChild(x))
return
def insertKey(x):
global curr_size
heap[curr_size] = x
curr_size += 1
heapify()
def deleteKey(i):
global curr_size
if i >= curr_size:
return
heap[i] = heap[curr_size - 1]
heap[curr_size - 1] = 0
curr_size -= 1
heapifyDown(i)
def extractMin():
if curr_size == 0:
return -1
val = heap[0]
deleteKey(0)
return val | FUNC_DEF RETURN BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER VAR BIN_OP BIN_OP NUMBER VAR NUMBER NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER VAR BIN_OP BIN_OP NUMBER VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR BIN_OP VAR NUMBER WHILE FUNC_CALL VAR VAR NUMBER VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN FUNC_DEF IF VAR VAR RETURN IF FUNC_CALL VAR VAR NUMBER VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR VAR VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR NUMBER VAR VAR VAR FUNC_CALL VAR VAR RETURN IF FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR RETURN FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR FUNC_DEF IF VAR VAR RETURN ASSIGN VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify2(i):
global heap
p = (i - 1) // 2
while p >= 0 and heap[p] > heap[i]:
heap[p], heap[i] = heap[i], heap[p]
i, p = p, (p - 1) // 2
def insertKey(x):
global curr_size, heap
heap[curr_size] = x
curr_size += 1
heapify2(curr_size - 1)
def deleteKey(i):
global curr_size, heap
n = curr_size
if n == 0 or i >= n:
return -1
else:
heap[i] = -99999
heapify2(i)
extractMin()
def extractMin():
global heap, curr_size
if curr_size == 0:
return -1
res = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
heapify(0)
return res
def heapify(i):
global heap, curr_size
lc, rc = 2 * i + 1, 2 * i + 2
smallest = i
if lc < curr_size and heap[smallest] > heap[lc]:
smallest = lc
if rc < curr_size and heap[smallest] > heap[rc]:
smallest = rc
if smallest != i:
heap[i], heap[smallest] = heap[smallest], heap[i]
heapify(smallest) | FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR VAR IF VAR NUMBER VAR VAR RETURN NUMBER ASSIGN VAR VAR NUMBER EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def parent(i):
return (i - 1) // 2
def swap(i, j):
global heap
heap[i], heap[j] = heap[j], heap[i]
def heapifyparent(i):
while i > 0 and heap[i] < heap[parent(i)]:
swap(i, parent(i))
i = parent(i)
def heapify(i):
small = i
l = left(i)
r = right(i)
if l < curr_size and heap[small] > heap[l]:
small = l
if r < curr_size and heap[small] > heap[r]:
small = r
if small != i:
swap(i, small)
heapify(small)
def decreasekey(i, x):
global heap, curr_size
if i < curr_size and x < heap[i]:
heap[i] = x
heapifyparent(i)
return True
return False
def insertKey(x):
global curr_size, heap
if curr_size == 101:
return False
heap[curr_size] = x
curr_size += 1
heapifyparent(curr_size - 1)
def deleteKey(i):
global curr_size
if i < curr_size:
decreasekey(i, -9223372036854775806)
extractMin()
else:
return -1
def extractMin():
global curr_size, heap
if curr_size == 0:
return -1
if curr_size == 1:
curr_size -= 1
return heap[0]
swap(0, curr_size - 1)
curr_size -= 1
heapify(0)
return heap[curr_size] | FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR FUNC_DEF WHILE VAR NUMBER VAR VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR VAR VAR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN NUMBER RETURN NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR RETURN NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER VAR NUMBER RETURN VAR NUMBER EXPR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def swim(i):
if i == 0:
return
parent_ind = (i - 1) // 2
if heap[i] < heap[parent_ind]:
heap[i], heap[parent_ind] = heap[parent_ind], heap[i]
swim(parent_ind)
def sink(i):
global curr_size
if i > curr_size:
return
lc_ind, rc_ind = 2 * i + 1, 2 * i + 2
lc_val = rc_val = float("inf")
if lc_ind < curr_size:
lc_val = heap[lc_ind]
if rc_ind < curr_size:
rc_val = heap[rc_ind]
if heap[i] > min(lc_val, rc_val):
if lc_val <= rc_val:
heap[i], heap[lc_ind] = heap[lc_ind], heap[i]
sink(lc_ind)
else:
heap[i], heap[rc_ind] = heap[rc_ind], heap[i]
sink(rc_ind)
def insertKey(x):
global curr_size
heap[curr_size] = x
curr_size += 1
swim(curr_size - 1)
def deleteKey(i):
global curr_size
if i >= curr_size:
return
curr_size -= 1
heap[i] = heap[curr_size]
sink(i)
swim(i)
def extractMin():
global curr_size
if curr_size == 0:
return -1
ret = heap[0]
curr_size -= 1
heap[0] = heap[curr_size]
sink(0)
return ret | FUNC_DEF IF VAR NUMBER RETURN ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR VAR RETURN ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR STRING IF VAR VAR ASSIGN VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR IF VAR VAR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER FUNC_DEF IF VAR VAR RETURN VAR NUMBER ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER VAR NUMBER ASSIGN VAR NUMBER VAR VAR EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def minHeapify(i):
global curr_size, heap
m = i
l = 2 * i + 1
r = l + 1
if l < curr_size and heap[l] < heap[m]:
m = l
if r < curr_size and heap[r] < heap[m]:
m = r
if i != m:
t = heap[i]
heap[i] = heap[m]
heap[m] = t
minHeapify(m)
def insertKey(x):
global curr_size, heap
if curr_size == 0:
heap[0] = x
curr_size = 1
return
heap[curr_size] = x
curr_size += 1
c = curr_size - 1
while c > 0:
p = int((c - 1) / 2)
if heap[p] > heap[c]:
t = heap[p]
heap[p] = heap[c]
heap[c] = t
c = p
else:
break
def deleteKey(i):
global curr_size, heap
if i >= curr_size:
return -1
if curr_size < 2:
curr_size = 0
return
if i == curr_size - 1:
curr_size -= 1
return
c = i
heap[i] = -999999
while c > 0:
p = int((c - 1) / 2)
if heap[p] > heap[c]:
t = heap[p]
heap[p] = heap[c]
heap[c] = t
c = p
else:
break
extractMin()
def extractMin():
global curr_size, heap
if curr_size == 0:
return -1
if curr_size == 1:
curr_size = 0
return heap[0]
temp = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
minHeapify(0)
return temp | FUNC_DEF ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NUMBER ASSIGN VAR NUMBER VAR ASSIGN VAR NUMBER RETURN ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR FUNC_DEF IF VAR VAR RETURN NUMBER IF VAR NUMBER ASSIGN VAR NUMBER RETURN IF VAR BIN_OP VAR NUMBER VAR NUMBER RETURN ASSIGN VAR VAR ASSIGN VAR VAR NUMBER WHILE VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER ASSIGN VAR NUMBER RETURN VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def insertKey(x):
global curr_size
heap[curr_size] = x
curr_size += 1
i = curr_size - 1
while i != 0 and heap[(i - 1) // 2] > heap[i]:
heap[(i - 1) // 2], heap[i] = heap[i], heap[(i - 1) // 2]
i = (i - 1) // 2
def minheapify(arr, n, i):
smallest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[l] < arr[smallest]:
smallest = l
if r < n and arr[r] < arr[smallest]:
smallest = r
if smallest != i:
arr[smallest], arr[i] = arr[i], arr[smallest]
minheapify(arr, n, smallest)
def decreaseKey(i, val):
if 0 <= i < curr_size:
heap[i] = val
while i != 0 and heap[i] < heap[(i - 1) // 2]:
heap[i], heap[(i - 1) // 2] = heap[(i - 1) // 2], heap[i]
i = (i - 1) // 2
def deleteKey(i):
global curr_size
if 0 <= i < curr_size:
if curr_size == 1:
curr_size -= 1
return
decreaseKey(i, float("-inf"))
extractMin()
def extractMin():
global curr_size
if curr_size == 0:
return -1
if curr_size == 1:
curr_size -= 1
return heap[0]
heap[curr_size - 1], heap[0] = heap[0], heap[curr_size - 1]
item = heap[curr_size - 1]
curr_size -= 1
minheapify(heap, curr_size, 0)
return item | FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF IF NUMBER VAR VAR ASSIGN VAR VAR VAR WHILE VAR NUMBER VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF IF NUMBER VAR VAR IF VAR NUMBER VAR NUMBER RETURN EXPR FUNC_CALL VAR VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER VAR NUMBER RETURN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER VAR NUMBER VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify(i):
p = (i - 1) // 2
while p >= 0:
if heap[p] > heap[i]:
heap[p], heap[i] = heap[i], heap[p]
i = p
p = (p - 1) // 2
def insertKey(x):
global curr_size
heap[curr_size] = x
heapify(curr_size)
curr_size = curr_size + 1
def heapify2(i):
global curr_size
l = i * 2 + 1
r = i * 2 + 2
k = i
if l < curr_size and heap[l] < heap[i]:
i = l
if r < curr_size and heap[r] < heap[i]:
i = r
if i != k:
heap[i], heap[k] = heap[k], heap[i]
heapify2(i)
def deleteKey(i):
global curr_size
if i >= curr_size:
return -1
heap[i] = float("-inf")
heapify(i)
heap[0] = heap[curr_size - 1]
heap[curr_size - 1] = 0
curr_size = curr_size - 1
heapify2(0)
def extractMin():
global curr_size
if curr_size == 0:
return -1
pos = heap[0]
heap[0] = heap[curr_size - 1]
heap[curr_size - 1] = 0
curr_size = curr_size - 1
heapify2(0)
return pos | FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER FUNC_DEF ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR VAR RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify(i):
global curr_size, heap
smallest = i
while True:
l, r = 2 * i + 1, 2 * i + 2
if l < curr_size and heap[smallest] > heap[l]:
smallest = l
if r < curr_size and heap[smallest] > heap[r]:
smallest = r
if smallest != i:
heap[smallest], heap[i] = heap[i], heap[smallest]
i = smallest
else:
break
def insertKey(x):
global curr_size, heap
heap[curr_size] = x
curr_size += 1
i = curr_size - 1
while i > 0:
parent = (i - 1) // 2
if heap[parent] > heap[i]:
heap[parent], heap[i] = heap[i], heap[parent]
i = parent
else:
break
def deleteKey(i):
global heap, curr_size
if i >= curr_size:
return -1
heap[i] = float("-inf")
while i > 0:
parent = (i - 1) // 2
if heap[parent] > heap[i]:
heap[parent], heap[i] = heap[i], heap[parent]
i = parent
else:
break
extractMin()
def extractMin():
global heap, curr_size
if curr_size == 0:
return -1
min_val = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
heapify(0)
return min_val | FUNC_DEF ASSIGN VAR VAR WHILE NUMBER ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_DEF IF VAR VAR RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR STRING WHILE VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def insertKey(x):
global curr_size
if curr_size >= 101:
return
curr_size += 1
decreaseKey(curr_size - 1, x)
def deleteKey(i):
global curr_size
if i >= curr_size:
return
decreaseKey(i, -float("inf"))
extractMin()
def extractMin():
global curr_size
if curr_size == 0:
return -1
if curr_size == 1:
curr_size -= 1
return heap[0]
ans = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
heapify(0)
return ans
def decreaseKey(i, new):
heap[i] = new
while i != 0 and heap[parent(i)] > heap[i]:
heap[i], heap[parent(i)] = heap[parent(i)], heap[i]
i = parent(i)
def heapify(i):
global curr_size
l = 2 * i + 1
r = 2 * i + 2
smallest = i
if l < curr_size and heap[l] < heap[smallest]:
smallest = l
if r < curr_size and heap[r] < heap[smallest]:
smallest = r
if smallest != i:
heap[i], heap[smallest] = heap[smallest], heap[i]
heapify(smallest)
def parent(i):
return (i - 1) // 2 | FUNC_DEF IF VAR NUMBER RETURN VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR NUMBER VAR FUNC_DEF IF VAR VAR RETURN EXPR FUNC_CALL VAR VAR FUNC_CALL VAR STRING EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER IF VAR NUMBER VAR NUMBER RETURN VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR VAR VAR WHILE VAR NUMBER VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF RETURN BIN_OP BIN_OP VAR NUMBER NUMBER |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify_up(i):
if i <= 0:
return
p_idx = (i - 1) // 2
if heap[p_idx] > heap[i]:
heap[p_idx], heap[i] = heap[i], heap[p_idx]
heapify_up(p_idx)
def heapify_down(i):
global curr_size
global heap
l_idx, r_idx = 2 * i + 1, 2 * i + 2
min_idx, smallest = i, heap[i]
if l_idx < curr_size and smallest > heap[l_idx]:
min_idx = l_idx
smallest = heap[l_idx]
if r_idx < curr_size and smallest > heap[r_idx]:
min_idx = r_idx
smallest = heap[r_idx]
if min_idx != i:
heap[i], heap[min_idx] = heap[min_idx], heap[i]
heapify_down(min_idx)
def insertKey(x):
global curr_size
global heap
heap[curr_size] = x
heapify_up(curr_size)
curr_size += 1
def deleteKey(i):
global heap
global curr_size
if i >= curr_size:
return
heap[i] = heap[curr_size - 1]
curr_size -= 1
if i < curr_size:
heapify_down(i)
heapify_up(i)
def extractMin():
global curr_size
global heap
if curr_size > 0:
min_value = heap[0]
heap[0] = heap[curr_size - 1]
curr_size -= 1
heapify_down(0)
return min_value
return -1 | FUNC_DEF IF VAR NUMBER RETURN ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR BIN_OP BIN_OP NUMBER VAR NUMBER BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR IF VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER FUNC_DEF IF VAR VAR RETURN ASSIGN VAR VAR VAR BIN_OP VAR NUMBER VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR RETURN NUMBER |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def insertKey(x):
global curr_size
heap[curr_size] = x
curr_size += 1
indx = curr_size - 1
while indx > 0 and heap[(indx - 1) // 2] > heap[indx]:
heap[(indx - 1) // 2], heap[indx] = heap[indx], heap[(indx - 1) // 2]
indx = (indx - 1) // 2
def deleteKey(i):
global curr_size
if curr_size <= i:
return
heap[i] = float("-inf")
indx = i
while indx > 0 and heap[(indx - 1) // 2] > heap[indx]:
heap[(indx - 1) // 2], heap[indx] = heap[indx], heap[(indx - 1) // 2]
indx = (indx - 1) // 2
extractMin()
def extractMin():
global curr_size
if curr_size == 0:
return -1
heap[0], heap[curr_size - 1] = heap[curr_size - 1], heap[0]
ext = heap.pop(curr_size - 1)
curr_size -= 1
heapify(0)
return ext
def heapify(indx):
global curr_size
left_indx = 2 * indx + 1
right_indx = 2 * indx + 2
smallest = indx
if left_indx < curr_size and heap[left_indx] < heap[indx]:
smallest = left_indx
if right_indx < curr_size and heap[smallest] > heap[right_indx]:
smallest = right_indx
if smallest != indx:
heap[indx], heap[smallest] = heap[smallest], heap[indx]
heapify(smallest) | FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF IF VAR VAR RETURN ASSIGN VAR VAR FUNC_CALL VAR STRING ASSIGN VAR VAR WHILE VAR NUMBER VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER VAR VAR VAR VAR VAR BIN_OP BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR BIN_OP VAR NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def parent(i):
return (i - 1) // 2
def leftchild(i):
return 2 * i + 1
def rightchild(i):
return 2 * i + 2
def insertKey(x):
global curr_size
heap[curr_size] = x
curr_size += 1
i = curr_size - 1
while i > 0 and heap[parent(i)] > heap[i]:
p = parent(i)
heap[i], heap[p] = heap[p], heap[i]
i = p
def decreasekey(index, value):
global curr_size
if index > curr_size:
return
heap[index] = value
i = index
while i != 0 and heap[parent(i)] > heap[i]:
p = parent(i)
heap[i], heap[p] = heap[p], heap[i]
i = p
def deleteKey(i):
global curr_size
if curr_size == 0:
return
if i >= curr_size:
return
decreasekey(i, -1)
extractMin()
return
def minifyheap(index):
global curr_size
if curr_size == 0:
return
lt = leftchild(index)
rt = rightchild(index)
smallest = index
if lt < curr_size and heap[lt] < heap[smallest]:
smallest = lt
if rt < curr_size and heap[rt] < heap[smallest]:
smallest = rt
if smallest != index:
heap[smallest], heap[index] = heap[index], heap[smallest]
minifyheap(smallest)
def extractMin():
global curr_size
if curr_size == 0:
return -1
output = heap[0]
heap[0] = heap[curr_size - 1]
heap[curr_size - 1] = 0
curr_size -= 1
minifyheap(0)
return output | FUNC_DEF RETURN BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF RETURN BIN_OP BIN_OP NUMBER VAR NUMBER FUNC_DEF ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_DEF IF VAR VAR RETURN ASSIGN VAR VAR VAR ASSIGN VAR VAR WHILE VAR NUMBER VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_DEF IF VAR NUMBER RETURN IF VAR VAR RETURN EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR RETURN FUNC_DEF IF VAR NUMBER RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER EXPR FUNC_CALL VAR NUMBER RETURN VAR |
A binary heap is a Binary Tree with the following properties:
1) Its a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
You are given an empty Binary Min Heap and some queries and your task is to implement the three methods insertKey, deleteKey, and extractMin on the Binary Min Heap and call them as per the query given below:
1) 1 x (a query of this type means to insert an element in the min-heap with value x )
2) 2 x (a query of this type means to remove an element at position x from the min-heap)
3) 3 (a query like this removes the min element from the min-heap and prints it ).
Example 1:
Input:
Q = 7
Queries:
insertKey(4)
insertKey(2)
extractMin()
insertKey(6)
deleteKey(0)
extractMin()
extractMin()
Output: 2 6 - 1
Explanation: In the first test case for
query
insertKey(4) the heap will have {4}
insertKey(2) the heap will be {2 4}
extractMin() removes min element from
heap ie 2 and prints it
now heap is {4}
insertKey(6) inserts 6 to heap now heap
is {4 6}
deleteKey(0) delete element at position 0
of the heap,now heap is {6}
extractMin() remove min element from heap
ie 6 and prints it now the
heap is empty
extractMin() since the heap is empty thus
no min element exist so -1
is printed.
Example 2:
Input:
Q = 5
Queries:
insertKey(8)
insertKey(9)
deleteKey(1)
extractMin()
extractMin()
Output: 8 -1
Your Task:
You are required to complete the 3 methods insertKey() which take one argument the value to be inserted, deleteKey() which takes one argument the position from where the element is to be deleted and extractMin() which returns the minimum element in the heap(-1 if the heap is empty)
Expected Time Complexity: O(Q*Log(size of Heap) ).
Expected Auxiliary Space: O(1).
Constraints:
1 <= Q <= 10^{4}
1 <= x <= 10^{4} | def heapify(heap, i):
global curr_size
left = 2 * i + 1
right = 2 * i + 2
if left < curr_size and heap[i] > heap[left]:
mini = left
else:
mini = i
if right < curr_size and heap[mini] > heap[right]:
mini = right
if i != mini:
heap[mini], heap[i] = heap[i], heap[mini]
heapify(heap, mini)
def insertKey(x):
global curr_size
heap[curr_size] = x
i = curr_size
curr_size += 1
parent = (i - 1) // 2
while parent >= 0 and heap[parent] > heap[i]:
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
parent = (parent - 1) // 2
def deleteKey(i):
global curr_size
if i >= curr_size or curr_size == 0:
return -1
heap[i] = float("-inf")
parent = (i - 1) // 2
while parent >= 0 and heap[parent] > heap[i]:
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
parent = (parent - 1) // 2
extractMin()
def extractMin():
global curr_size
if curr_size == 0:
return -1
mini = heap[0]
heap[0] = heap[curr_size - 1]
heap[curr_size - 1] = 0
curr_size -= 1
heapify(heap, 0)
return mini | FUNC_DEF ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER ASSIGN VAR BIN_OP BIN_OP NUMBER VAR NUMBER IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR IF VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER FUNC_DEF IF VAR VAR VAR NUMBER RETURN NUMBER ASSIGN VAR VAR FUNC_CALL VAR STRING ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER WHILE VAR NUMBER VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR NUMBER NUMBER EXPR FUNC_CALL VAR FUNC_DEF IF VAR NUMBER RETURN NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR NUMBER VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER NUMBER VAR NUMBER EXPR FUNC_CALL VAR VAR NUMBER RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, root):
myMap = {}
def dfs(node):
if not node:
return
if node not in myMap:
clone = Node(node.data)
myMap[node] = clone
else:
return myMap[node]
clone.left = dfs(node.left)
clone.right = dfs(node.right)
clone.random = dfs(node.random)
return clone
return dfs(root) | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF IF VAR RETURN IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR RETURN FUNC_CALL VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if tree:
a = Node(tree.data)
if tree.random:
a.random = Node(tree.random.data)
a.left = self.cloneTree(tree.left)
a.right = self.cloneTree(tree.right)
return a
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.random = None
def __str__(self):
return str(self.data)
def printInord(a, b):
if not a and not b:
return 1
if a and b:
t = int(
a.data == b.data
and printInord(a.left, b.left)
and printInord(a.right, b.right)
)
if a.random and b.random:
return int(t and a.random.data == b.random.data)
if a.random == b.random:
return t
return 0
return 0
if __name__ == "__main__":
tcs = int(input())
for _ in range(tcs):
map = dict()
n = int(input())
arrnode = [x for x in input().split()]
root = None
i = 0
while i < 3 * n:
n1, n2, lr = int(arrnode[i]), int(arrnode[i + 1]), arrnode[i + 2]
if n1 in map:
parent = map[n1]
else:
parent = Node(n1)
map[n1] = parent
if not root:
root = parent
child = Node(n2)
map[n2] = child
if lr == "R":
parent.right = child
elif lr == "L":
parent.left = child
else:
parent.random = map[n2]
i += 3
ansTree = Solution().cloneTree(root)
if ansTree == root:
print(0)
else:
print(int(printInord(root, ansTree))) | CLASS_DEF FUNC_DEF IF VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR CLASS_DEF FUNC_DEF ASSIGN VAR VAR ASSIGN VAR NONE ASSIGN VAR NONE ASSIGN VAR NONE FUNC_DEF RETURN FUNC_CALL VAR VAR FUNC_DEF IF VAR VAR RETURN NUMBER IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR IF VAR VAR RETURN FUNC_CALL VAR VAR VAR VAR IF VAR VAR RETURN VAR RETURN NUMBER RETURN NUMBER IF VAR STRING ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR NONE ASSIGN VAR NUMBER WHILE VAR BIN_OP NUMBER VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR BIN_OP VAR NUMBER IF VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR STRING ASSIGN VAR VAR IF VAR STRING ASSIGN VAR VAR ASSIGN VAR VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL FUNC_CALL VAR VAR IF VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
mapp = {}
cloned_root = self.cloneUtil(tree, mapp)
return cloned_root
def cloneUtil(self, root, mapp):
if root in mapp:
return mapp[root]
if not root:
return
node = Node(root.data)
mapp[root] = node
if root.left:
mapp[root].left = self.cloneUtil(root.left, mapp)
if root.right:
mapp[root].right = self.cloneUtil(root.right, mapp)
if root.random:
mapp[root].random = self.cloneUtil(root.random, mapp)
return mapp[root] | CLASS_DEF FUNC_DEF ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF IF VAR VAR RETURN VAR VAR IF VAR RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR IF VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR IF VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
visit = set()
def dfs(root):
if root == None:
return
if root in visit:
return
visit.add(root)
copy = Node(root.data)
copy.left = dfs(root.left)
copy.right = dfs(root.right)
copy.random = dfs(root.random)
visit.remove(root)
return copy
return dfs(root) | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_DEF IF VAR NONE RETURN IF VAR VAR RETURN EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR RETURN FUNC_CALL VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
root = Node(tree.data)
qq = []
qq.append(root)
qq.append(None)
hm = {}
q = []
q.append(tree)
q.append(None)
while q:
temp = q.pop(0)
curr = qq.pop(0)
if temp == None and q:
q.append(None)
qq.append(None)
elif temp == None and q == []:
break
else:
if temp.left:
q.append(temp.left)
curr.left = Node(temp.left.data)
qq.append(curr.left)
if temp.right:
q.append(temp.right)
curr.right = Node(temp.right.data)
qq.append(curr.right)
hm[temp] = curr
q.append(tree)
q.append(None)
qq.append(root)
qq.append(None)
while q:
temp = q.pop(0)
curr = qq.pop(0)
if temp == None and q:
q.append(None)
qq.append(None)
elif temp == None and q == []:
break
else:
if temp.left:
q.append(temp.left)
qq.append(curr.left)
if temp.right:
q.append(temp.right)
qq.append(curr.right)
if temp.random:
if hm.get(temp.random):
curr.random = hm[temp.random]
else:
curr.random = Node(temp.random.data)
return root | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NONE ASSIGN VAR DICT ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NONE WHILE VAR ASSIGN VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER IF VAR NONE VAR EXPR FUNC_CALL VAR NONE EXPR FUNC_CALL VAR NONE IF VAR NONE VAR LIST IF VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NONE EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR NONE WHILE VAR ASSIGN VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER IF VAR NONE VAR EXPR FUNC_CALL VAR NONE EXPR FUNC_CALL VAR NONE IF VAR NONE VAR LIST IF VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR IF FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def traverse_tree(self, tree):
self.c += 1
tree.c = self.c
if tree.left is not None:
self.traverse_tree(tree.left)
if tree.right is not None:
self.traverse_tree(tree.right)
def copy_recursively(self, tree):
node = Node(data=tree.data)
self.found[tree.data] = node
if tree.left is not None:
node.left = self.copy_recursively(tree.left)
if tree.right is not None:
node.right = self.copy_recursively(tree.right)
return node
def copy_random_pointer(self, tree, new_tree):
if tree.random is not None:
new_tree.random = self.found[tree.random.data]
if tree.left is not None:
self.copy_random_pointer(tree.left, new_tree.left)
if tree.right is not None:
self.copy_random_pointer(tree.right, new_tree.right)
def cloneTree(self, tree):
self.c = 0
self.traverse_tree(tree)
self.found = {}
new_tree = self.copy_recursively(tree)
self.c = 0
self.copy_random_pointer(tree, new_tree)
return new_tree | CLASS_DEF FUNC_DEF VAR NUMBER ASSIGN VAR VAR IF VAR NONE EXPR FUNC_CALL VAR VAR IF VAR NONE EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF IF VAR NONE ASSIGN VAR VAR VAR IF VAR NONE EXPR FUNC_CALL VAR VAR VAR IF VAR NONE EXPR FUNC_CALL VAR VAR VAR FUNC_DEF ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER EXPR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def clone(self, node, d):
if not node:
return None
clone = Node(node.data)
d[node] = clone
clone.left = self.clone(node.left, d)
clone.right = self.clone(node.right, d)
return clone
def copyr(self, node, clone, d):
if not clone:
return
clone.random = d[node.random]
self.copyr(node.left, clone.left, d)
self.copyr(node.right, clone.right, d)
def cloneTree(self, tree):
if not tree:
return None
d = dict()
d[None] = None
clo = self.clone(tree, d)
self.copyr(clo, tree, d)
return clo | CLASS_DEF FUNC_DEF IF VAR RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF IF VAR RETURN ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF IF VAR RETURN NONE ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NONE NONE ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, root):
mapp = {}
root = self.cloneTreeUtil(root, mapp)
return root
def cloneTreeUtil(self, root, mapp):
if not root:
return None
if root.data not in mapp:
node = Node(root.data)
mapp[node.data] = node
if root.random:
val = mapp.get(root.random.data, None)
if not val:
node.random = Node(root.random.data)
else:
node.random = val
node.left = self.cloneTreeUtil(root.left, mapp)
node.right = self.cloneTreeUtil(root.right, mapp)
return node | CLASS_DEF FUNC_DEF ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF IF VAR RETURN NONE IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR NONE IF VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def simple_clone(self, root):
if root is None:
return None
else:
new_root = Node(root.data)
if root.random:
new_root.random = Node(root.random.data)
new_root.left = self.simple_clone(root.left)
new_root.right = self.simple_clone(root.right)
return new_root
def cloneTree(self, root):
new_root = self.simple_clone(root)
return new_root | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
def recursive(tree):
if tree is None:
return None
cur = Node(tree.data)
cur.left = recursive(tree.left)
cur.right = recursive(tree.right)
cur.random = tree.random
return cur
return recursive(tree) | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR RETURN FUNC_CALL VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree, random=False):
if tree is None:
return None
if random:
return tree
newNode = Node(tree.data)
newNode.left = self.cloneTree(tree.left)
newNode.right = self.cloneTree(tree.right)
newNode.random = self.cloneTree(tree.random, random=True)
return newNode | CLASS_DEF FUNC_DEF NUMBER IF VAR NONE RETURN NONE IF VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR NUMBER RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
n = Node(tree.data)
tq = [tree]
rq = [n]
visited = {}
while len(tq) > 0:
onode = tq.pop(0)
nnode = rq.pop(0)
if onode in visited:
continue
visited[onode] = True
if onode.left != None:
lnode = Node(onode.left.data)
nnode.left = lnode
if onode.left not in visited:
tq.append(onode.left)
rq.append(nnode.left)
if onode.right != None:
rnode = Node(onode.right.data)
nnode.right = rnode
if onode.right not in visited:
tq.append(onode.right)
rq.append(nnode.right)
if onode.random != None:
ranode = Node(onode.random.data)
nnode.random = ranode
if onode.random not in visited:
tq.append(onode.random)
rq.append(nnode.random)
return n | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST VAR ASSIGN VAR LIST VAR ASSIGN VAR DICT WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER IF VAR VAR ASSIGN VAR VAR NUMBER IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR IF VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def io(self, a):
if a:
self.io(a.left)
print(a.data, end=" ")
self.io(a.right)
def cloneTree(self, tree):
visited = {}
queue = [tree]
g = Node(tree.data)
queue1 = [g]
while len(queue) > 0:
x = queue.pop(0)
y = queue1.pop(0)
if x in visited:
continue
visited[x] = 1
if x.left:
y.left = Node(x.left.data)
queue.append(x.left)
queue1.append(y.left)
if x.right:
y.right = Node(x.right.data)
queue.append(x.right)
queue1.append(y.right)
if x.random:
y.random = Node(x.random.data)
queue.append(x.random)
queue1.append(y.random)
return g | CLASS_DEF FUNC_DEF IF VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR STRING EXPR FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR DICT ASSIGN VAR LIST VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR LIST VAR WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER IF VAR VAR ASSIGN VAR VAR NUMBER IF VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneLeftAndRight(self, node, cloneNode, visitedMap):
visitedMap[node.data] = cloneNode
if node.left:
cloneNode.left = Node(node.left.data)
self.cloneLeftAndRight(node.left, cloneNode.left, visitedMap)
if node.right:
cloneNode.right = Node(node.right.data)
self.cloneLeftAndRight(node.right, cloneNode.right, visitedMap)
def cloneRandom(self, node, cloneNode, visitedMap):
if node.random is not None:
cloneNode.random = visitedMap[node.random.data]
if node.left:
self.cloneRandom(node.left, cloneNode.left, visitedMap)
if node.right:
self.cloneRandom(node.right, cloneNode.right, visitedMap)
def cloneTree(self, tree):
visitedMap = {}
cloneRoot = Node(tree.data)
self.cloneLeftAndRight(tree, cloneRoot, visitedMap)
self.cloneRandom(tree, cloneRoot, visitedMap)
return cloneRoot | CLASS_DEF FUNC_DEF ASSIGN VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF IF VAR NONE ASSIGN VAR VAR VAR IF VAR EXPR FUNC_CALL VAR VAR VAR VAR IF VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if tree is None:
return None
hashMap = {}
newTree = self.cloneTreeUtil(tree, hashMap)
self.connectRandomPointer(tree, newTree, hashMap)
return newTree
def connectRandomPointer(self, tree, newTree, hashMap):
if tree is None:
return
if tree.random:
newRandom = hashMap[tree.random.data]
newTree.random = newRandom
self.connectRandomPointer(tree.left, newTree.left, hashMap)
self.connectRandomPointer(tree.right, newTree.right, hashMap)
def cloneTreeUtil(self, tree, hashMap):
if tree is None:
return
newTree = Node(tree.data)
hashMap[newTree.data] = newTree
newTree.left = self.cloneTreeUtil(tree.left, hashMap)
newTree.right = self.cloneTreeUtil(tree.right, hashMap)
return newTree | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NONE RETURN IF VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF IF VAR NONE RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if tree is None:
return None
hashMap = {}
newTree = self.cloneTreeUtil(tree, hashMap)
self.connectRandomTree(tree, newTree, hashMap)
return newTree
def cloneTreeUtil(self, tree, hashMap):
if tree is None:
return None
newNode = Node(tree.data)
hashMap[newNode.data] = newNode
newNode.left = self.cloneTreeUtil(tree.left, hashMap)
newNode.right = self.cloneTreeUtil(tree.right, hashMap)
return newNode
def connectRandomTree(self, tree, newTree, hashMap):
if tree is None:
return
if tree.random:
newTree.random = hashMap[tree.random.data]
self.connectRandomTree(tree.left, newTree.left, hashMap)
self.connectRandomTree(tree.right, newTree.right, hashMap) | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NONE RETURN IF VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if not tree:
return
temp = Node(tree.data)
temp.left = self.cloneTree(tree.left)
temp.right = self.cloneTree(tree.right)
temp.random = tree.random
return temp | CLASS_DEF FUNC_DEF IF VAR RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
root = self.clone(tree)
return root
def clone(self, root):
if root is None:
return None
else:
_node = Node(root.data)
if root.random is not None:
_node.random = Node(root.random.data)
_node.left = self.clone(root.left)
_node.right = self.clone(root.right)
return _node | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def inorder_data(self, root, ans):
if root:
self.inorder_data(root.left, ans)
ans[root] = Node(root.data)
self.inorder_data(root.right, ans)
def inorder_ans(self, root, ans):
if root:
self.inorder_ans(root.left, ans)
node = ans[root]
node.random = ans.get(root.random)
self.inorder_ans(root.right, ans)
def cloneTree(self, root):
if not root:
return None
node = Node(root.data)
node.left = self.cloneTree(root.left)
node.right = self.cloneTree(root.right)
node.random = root.random
return node | CLASS_DEF FUNC_DEF IF VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF IF VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF IF VAR RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
mp = dict()
s = []
s.append(tree)
while len(s) > 0:
c = s.pop()
temp = Node(c.data)
mp[c.data] = temp
if c.right:
s.append(c.right)
if c.left:
s.append(c.left)
s = []
s.append(tree)
while len(s) > 0:
c = s.pop()
if c.left:
mp[c.data].left = mp[c.left.data]
s.append(c.left)
else:
mp[c.data].left = None
if c.right:
mp[c.data].right = mp[c.right.data]
s.append(c.right)
else:
mp[c.data].right = None
if c.random:
mp[c.data].random = mp[c.random.data]
else:
mp[c.data].random = None
return mp[tree.data] | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR IF VAR EXPR FUNC_CALL VAR VAR IF VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR WHILE FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR IF VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR NONE IF VAR ASSIGN VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR NONE IF VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR NONE RETURN VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if not tree:
return tree
nodes = [tree]
first = prev = Node(None)
while nodes:
new_nodes = []
for node in nodes:
prev.data = node.data
prev.left = node.left
prev.right = node.right
prev.random = node.random
if node.left:
new_nodes.append(node.left)
if node.right:
new_nodes.append(node.right)
nodes = new_nodes
prev = Node(None)
return first | CLASS_DEF FUNC_DEF IF VAR RETURN VAR ASSIGN VAR LIST VAR ASSIGN VAR VAR FUNC_CALL VAR NONE WHILE VAR ASSIGN VAR LIST FOR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR IF VAR EXPR FUNC_CALL VAR VAR IF VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR NONE RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | def helper(root, d):
if root:
clone = Node(root.data)
d[root.data] = [root.random, clone]
clone.left = helper(root.left, d)
clone.right = helper(root.right, d)
return clone
def traverse(node, d):
if node:
temp = d[node.data]
if temp[0] is not None:
node.random = d[temp[0].data][1]
else:
node.random = None
traverse(node.left, d)
traverse(node.right, d)
class Solution:
def cloneTree(self, root):
if root:
d = {}
ans = helper(root, d)
traverse(ans, d)
return ans
return | FUNC_DEF IF VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR LIST VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF IF VAR ASSIGN VAR VAR VAR IF VAR NUMBER NONE ASSIGN VAR VAR VAR NUMBER NUMBER ASSIGN VAR NONE EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR CLASS_DEF FUNC_DEF IF VAR ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN VAR RETURN |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if not tree:
return
else:
if not tree.left and not tree.right:
return tree
root = Node(tree.data)
root.random = tree.random
root.left = self.cloneTree(tree.left)
root.right = self.cloneTree(tree.right)
return root | CLASS_DEF FUNC_DEF IF VAR RETURN IF VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
d = {}
def helper(node):
if node == None:
return None
clone = Node(node.data)
d[node.data] = [node.random, clone]
clone.left = helper(node.left)
clone.right = helper(node.right)
return clone
ans = helper(tree)
def traverse(node):
if node == None:
return None
temp = d[node.data]
if temp != None:
node.random = temp[0]
else:
node.random = None
traverse(node.left)
traverse(node.right)
traverse(ans)
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR LIST VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR VAR VAR IF VAR NONE ASSIGN VAR VAR NUMBER ASSIGN VAR NONE EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def preorder(self, root, po):
if root is None:
return
po.append(
[
root.data,
root.left.data if root.left else -1,
root.right.data if root.right else -1,
root.random.data if root.random else -1,
]
)
self.preorder(root.left, po)
self.preorder(root.right, po)
def dup_tree(self, po, idx, N, ht, rand):
if idx[0] >= N:
return
i = idx[0]
node = Node(po[i][0])
if node.data in ht:
ht[node.data].append(node)
else:
ht[node.data] = [node]
if po[i][3] != -1:
rand.append([node, po[i][3]])
if po[i][1] != -1:
idx[0] += 1
node.left = self.dup_tree(po, idx, N, ht, rand)
if po[i][2] != -1:
idx[0] += 1
node.right = self.dup_tree(po, idx, N, ht, rand)
return node
def cloneTree(self, tree):
po = []
ht = {}
rand = []
self.preorder(tree, po)
root = self.dup_tree(po, [0], len(po), ht, rand)
for r in rand:
node = r[0]
dnode = ht[r[1]][0]
node.random = dnode
return root | CLASS_DEF FUNC_DEF IF VAR NONE RETURN EXPR FUNC_CALL VAR LIST VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF IF VAR NUMBER VAR RETURN ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR LIST VAR IF VAR VAR NUMBER NUMBER EXPR FUNC_CALL VAR LIST VAR VAR VAR NUMBER IF VAR VAR NUMBER NUMBER VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR IF VAR VAR NUMBER NUMBER VAR NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR LIST ASSIGN VAR DICT ASSIGN VAR LIST EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR LIST NUMBER FUNC_CALL VAR VAR VAR VAR FOR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER NUMBER ASSIGN VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
dic = dict()
def rec(nod):
if nod is None:
return None
tem = Node(nod.data)
dic[nod.data] = tem.data
tem.left = rec(nod.left)
tem.right = rec(nod.right)
return tem
root = rec(tree)
def rec2(n, m):
if n is None or m is None:
return
m.random = n.random
rec2(n.left, m.left)
rec2(n.right, m.right)
rec2(tree, root)
return root | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE VAR NONE RETURN ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def c(self, h, he):
if h == None:
return
self.ra[h] = h.random
self.cl[h] = he
if h.left == None and h.right == None:
return
if h.left is not None:
he.left = Node(h.left.data)
self.cl[h.left] = he.left
self.c(h.left, he.left)
if h.right is not None:
he.right = Node(h.right.data)
self.cl[h.right] = he.right
self.c(h.right, he.right)
def cloneTree(self, tree):
self.cl = {}
self.ra = {}
he = Node(tree.data)
self.c(tree, he)
for i in self.ra:
if self.ra[i] is not None:
self.cl[i].random = self.ra[i]
return he | CLASS_DEF FUNC_DEF IF VAR NONE RETURN ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR IF VAR NONE VAR NONE RETURN IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF ASSIGN VAR DICT ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR FOR VAR VAR IF VAR VAR NONE ASSIGN VAR VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def clone(self, root):
if root is None:
return None
root_copy = Node(root.data)
root_copy.left = self.clone(root.left)
root_copy.right = self.clone(root.right)
return root_copy
def cloneRandom(self, clone_root, root):
if root is None:
return None
clone_root.random = root.random
self.cloneRandom(clone_root.left, root.left)
self.cloneRandom(clone_root.right, root.right)
return clone_root
def cloneTree(self, tree):
clone_root = self.clone(tree)
main_root = self.cloneRandom(clone_root, tree)
return main_root | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def copy(self, root, random, newptr):
if not root:
return
node = Node(root.data)
node.left = root.left
node.right = root.right
random[root.data] = root.random
newptr[node.data] = node
self.copy(root.left, random, newptr)
self.copy(root.right, random, newptr)
return node
def assign_random(self, root, random, newptr):
if not root:
return
if random[root.data]:
newptr[root.data].random = newptr[random[root.data].data]
self.assign_random(root.left, random, newptr)
self.assign_random(root.right, random, newptr)
def cloneTree(self, tree):
random = {}
newptr = {}
root = self.copy(tree, random, newptr)
self.assign_random(tree, random, newptr)
return root | CLASS_DEF FUNC_DEF IF VAR RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR RETURN IF VAR VAR ASSIGN VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR FUNC_DEF ASSIGN VAR DICT ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
a = Node(tree.data)
d = {tree.data: a}
rd = {}
q = [tree]
while q:
c = q.pop(0)
if c.left:
q.append(c.left)
d[c.data].left = Node(c.left.data)
d[c.left.data] = d[c.data].left
if c.right:
q.append(c.right)
d[c.data].right = Node(c.right.data)
d[c.right.data] = d[c.data].right
if c.random:
rd[c.data] = c.random.data
for k in rd:
d[k].random = d[rd[k]]
return a | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT VAR VAR ASSIGN VAR DICT ASSIGN VAR LIST VAR WHILE VAR ASSIGN VAR FUNC_CALL VAR NUMBER IF VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR IF VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR IF VAR ASSIGN VAR VAR VAR FOR VAR VAR ASSIGN VAR VAR VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
def _solve(nd):
if not nd:
return None
nodes.append(nd)
mp[nd.data] = new = Node(nd.data)
new.left = _solve(nd.left)
new.right = _solve(nd.right)
return new
nodes = []
mp = {}
new = _solve(tree)
for o in nodes:
if o.random is not None:
mp[o.data].random = mp[o.random.data]
return new | CLASS_DEF FUNC_DEF FUNC_DEF IF VAR RETURN NONE EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR ASSIGN VAR LIST ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR IF VAR NONE ASSIGN VAR VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def solve(self, root):
if root == None:
return
new = Node(root.data)
new.random = root.random
new.left = self.solve(root.left)
new.right = self.solve(root.right)
return new
def cloneTree(self, tree):
return self.solve(tree) | CLASS_DEF FUNC_DEF IF VAR NONE RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF RETURN FUNC_CALL VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if not tree:
return None
return self.dfs(tree, {})
def dfs(self, root, oldToNew):
if not root:
return None
if root in oldToNew:
return oldToNew[root]
newNode = Node(root.data)
oldToNew[root] = newNode
newNode.left = self.dfs(root.left, oldToNew)
newNode.right = self.dfs(root.right, oldToNew)
newNode.random = self.dfs(root.random, oldToNew)
return newNode | CLASS_DEF FUNC_DEF IF VAR RETURN NONE RETURN FUNC_CALL VAR VAR DICT FUNC_DEF IF VAR RETURN NONE IF VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def clone_tree_util(self, root, mp):
if root is None:
return None
if root in mp:
return mp[root]
cloned_node = Node(root.data)
mp[root] = cloned_node
cloned_node.left = self.clone_tree_util(root.left, mp)
cloned_node.right = self.clone_tree_util(root.right, mp)
cloned_node.random = self.clone_tree_util(root.random, mp)
return cloned_node
def cloneTree(self, tree):
mp = {}
return self.clone_tree_util(tree, mp) | CLASS_DEF FUNC_DEF IF VAR NONE RETURN NONE IF VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR DICT RETURN FUNC_CALL VAR VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def helper(self, node1, node2):
if node1 is None:
return
self.d1[node1] = node2
if node1.left:
node2.left = Node(node1.left.data)
if node1.left.random:
node2.left.random = self.d1[node1.left.random]
self.helper(node1.left, node2.left)
if node1.right:
node2.right = Node(node1.right.data)
if node1.right.random:
node2.right.random = self.d1[node1.right.random]
self.helper(node1.right, node2.right)
def cloneTree(self, tree):
if not tree:
return None
tree1 = Node(tree.data)
self.d1 = {}
self.helper(tree, tree1)
return tree1
class Solution:
def cloneTree(self, tree):
d = {}
def node(tree):
if not tree:
return
if tree not in d:
root = Node(tree.data)
d[tree] = root
else:
return d[tree]
root.left = node(tree.left)
root.right = node(tree.right)
root.random = node(tree.random)
return root
return node(tree) | CLASS_DEF FUNC_DEF IF VAR NONE RETURN ASSIGN VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR ASSIGN VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF IF VAR RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR DICT EXPR FUNC_CALL VAR VAR VAR RETURN VAR CLASS_DEF FUNC_DEF ASSIGN VAR DICT FUNC_DEF IF VAR RETURN IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR RETURN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR RETURN FUNC_CALL VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
if not tree:
return
if tree.left is None and tree.right is None:
root = Node(tree.data)
root.random = tree.random
return root
root = Node(tree.data)
root.left = self.cloneTree(tree.left)
root.right = self.cloneTree(tree.right)
root.random = self.cloneTree(tree.random)
return root | CLASS_DEF FUNC_DEF IF VAR RETURN IF VAR NONE VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def clone(self, tree, dict):
if tree != None:
node = Node(tree.data)
node.left = self.clone(tree.left, dict)
node.right = self.clone(tree.right, dict)
dict[node] = tree
return node
def cloneTree(self, tree):
dict = {}
node = self.clone(tree, dict)
for i in dict.keys():
i.random = dict[i].random
return node | CLASS_DEF FUNC_DEF IF VAR NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR DICT ASSIGN VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR ASSIGN VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def makenode(self, root):
if not root:
return
node = Node(root.data)
node.left = root.left
node.right = root.right
root.left = node
self.makenode(node.left)
self.makenode(node.right)
def connectrandom(self, root):
if root == None:
return
root.left.random = root.random
self.connectrandom(root.left.left)
self.connectrandom(root.left.right)
def clone(self, root, node):
if root == None:
return
root.left = node.left
if node.left:
node.left = node.left.left
if node.right:
node.right = node.right.left
self.clone(root.left, node.left)
self.clone(root.right, node.right)
def cloneTree(self, tree):
self.makenode(tree)
node = tree.left
self.connectrandom(tree)
self.clone(tree, node)
return node | CLASS_DEF FUNC_DEF IF VAR RETURN ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE RETURN ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR FUNC_DEF IF VAR NONE RETURN ASSIGN VAR VAR IF VAR ASSIGN VAR VAR IF VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR FUNC_DEF EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR RETURN VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | def fun(tree, d):
if tree == None:
return None
if tree in d:
pass
else:
root = Node(0)
root.data = tree.data
d[tree] = 1
root.left = fun(tree.left, d)
root.right = fun(tree.right, d)
root.random = fun(tree.random, d)
return root
class Solution:
def cloneTree(self, tree):
d = {}
return fun(tree, d) | FUNC_DEF IF VAR NONE RETURN NONE IF VAR VAR ASSIGN VAR FUNC_CALL VAR NUMBER ASSIGN VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR CLASS_DEF FUNC_DEF ASSIGN VAR DICT RETURN FUNC_CALL VAR VAR VAR |
Given a special binary tree having random pointers along with the usual left and right pointers. Clone the given tree.
Example 1:
Input:
Output: 1
Explanation: The tree was cloned successfully.
Your Task:
No need to read input or print anything. Complete the function cloneTree() which takes root of the given tree as input parameter and returns the root of the cloned tree.
Note: The output is 1 if the tree is cloned successfully. Otherwise output is 0.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 100
1 ≤ Data of a node ≤ 1000 | class Solution:
def cloneTree(self, tree):
hashTable = {}
if tree == None:
return tree
newRoot = self.preorder(tree, hashTable)
for node in hashTable:
if node.random not in hashTable:
if node.random == None:
hashTable[node].random = None
else:
hashTable[node].random = Node(node.random.data)
else:
hashTable[node].random = hashTable[node.random]
return newRoot
def preorder(self, root, hashTable):
if root == None:
return None
newNode = Node(root.data)
hashTable[root] = newNode
newNode.left = self.preorder(root.left, hashTable)
newNode.right = self.preorder(root.right, hashTable)
return newNode | CLASS_DEF FUNC_DEF ASSIGN VAR DICT IF VAR NONE RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FOR VAR VAR IF VAR VAR IF VAR NONE ASSIGN VAR VAR NONE ASSIGN VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR FUNC_DEF IF VAR NONE RETURN NONE ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR |
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Ridbit is given an array $a_{1}, a_{2}, \ldots, a_{N}$. He needs to find the number of ways to divide the array into contiguous subarrays such that:
Each element of the sequence $a$ belongs to exactly one of the subarrays.
There is an integer $m$ such that the MEX of every subarray is equal to $m$. The MEX of a sequence is the smallest non-negative integer which does not occur in this sequence.
Help Ridbit with this task.
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first line of each test case contains a single integer $N$.
The second line contains $N$ space-separated integers $a_{1}, a_{2}, \ldots, a_{N}$.
------ Output ------
For each test case, print a single line containing one integer ― the number of ways to divide the sequence, modulo $10^{9} + 7$.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 100,000$
$0 ≤ a_{i} ≤ N$ for each valid $i$
----- Sample Input 1 ------
2
6
1 0 0 1 0 1
3
1 2 3
----- Sample Output 1 ------
5
4
----- explanation 1 ------
Example case 1: The five valid ways to divide the sequence are:
- $[1, 0, 0, 1, 0, 1]$
- $[1, 0], [0, 1, 0, 1]$
- $[1, 0, 0], [1, 0, 1]$
- $[1, 0, 0, 1], [0, 1]$
- $[1, 0], [0, 1], [0, 1]$ | mod = 10**9 + 7
t = int(input())
for i in range(t):
n = int(input())
arr = [int(x) for x in input().split()]
l = sorted(arr)
prev = -1
for i in range(n):
if l[i] - prev > 1:
break
prev = l[i]
m = prev + 1
d = {}
for i in range(n):
if arr[i] > m:
continue
d[arr[i]] = d.get(arr[i], 0) + 1
p = n - 1
while p >= 0:
if arr[p] < m:
if d[arr[p]] == 1:
break
else:
d[arr[p]] = d[arr[p]] - 1
p = p - 1
p = p + 1
p = max(1, p)
dp = [0] * (n + 1)
pref = [0] * (n + 1)
dp[0] = 1
pref[0] = 1
for i in range(1, p):
dp[i] = 0
pref[i] = 1
dp[p] = 1
pref[p] = 2
p = p + 1
prev = 1
while p <= n:
if arr[p - 1] < m:
d[arr[p - 1]] = d[arr[p - 1]] + 1
while prev < p:
if arr[prev - 1] < m:
if d[arr[prev - 1]] == 1:
break
else:
d[arr[prev - 1]] = d[arr[prev - 1]] - 1
prev = prev + 1
dp[p] = pref[prev - 1]
pref[p] = (pref[p - 1] + dp[p]) % mod
p = p + 1
print(dp[n]) | ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER 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 VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF BIN_OP VAR VAR VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR DICT FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP FUNC_CALL VAR VAR VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR NUMBER IF VAR VAR VAR IF VAR VAR VAR NUMBER ASSIGN VAR VAR VAR BIN_OP VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR NUMBER NUMBER ASSIGN VAR NUMBER NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR BIN_OP VAR NUMBER NUMBER WHILE VAR VAR IF VAR BIN_OP VAR NUMBER VAR IF VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR BIN_OP VAR NUMBER BIN_OP VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR VAR BIN_OP BIN_OP VAR BIN_OP VAR NUMBER VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER EXPR FUNC_CALL VAR VAR VAR |
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Ridbit is given an array $a_{1}, a_{2}, \ldots, a_{N}$. He needs to find the number of ways to divide the array into contiguous subarrays such that:
Each element of the sequence $a$ belongs to exactly one of the subarrays.
There is an integer $m$ such that the MEX of every subarray is equal to $m$. The MEX of a sequence is the smallest non-negative integer which does not occur in this sequence.
Help Ridbit with this task.
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first line of each test case contains a single integer $N$.
The second line contains $N$ space-separated integers $a_{1}, a_{2}, \ldots, a_{N}$.
------ Output ------
For each test case, print a single line containing one integer ― the number of ways to divide the sequence, modulo $10^{9} + 7$.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 100,000$
$0 ≤ a_{i} ≤ N$ for each valid $i$
----- Sample Input 1 ------
2
6
1 0 0 1 0 1
3
1 2 3
----- Sample Output 1 ------
5
4
----- explanation 1 ------
Example case 1: The five valid ways to divide the sequence are:
- $[1, 0, 0, 1, 0, 1]$
- $[1, 0], [0, 1, 0, 1]$
- $[1, 0, 0], [1, 0, 1]$
- $[1, 0, 0, 1], [0, 1]$
- $[1, 0], [0, 1], [0, 1]$ | T = int(input())
P = 10**9 + 7
for _ in range(T):
N = int(input())
A = [int(x) for x in input().split()]
S = set(A)
MEX = 0
while True:
if MEX not in S:
break
MEX += 1
if MEX == 0:
print(pow(2, N - 1, P))
continue
S1 = set(range(MEX))
end_index = N - 1
while True:
if not S1:
break
if A[end_index] in S1:
S1.remove(A[end_index])
end_index -= 1
if end_index < 0:
break
S1 = set(range(MEX))
start_index = 0
last_seen = [(-1) for _ in range(MEX)]
while True:
if not S1:
break
if A[start_index] < MEX:
last_seen[A[start_index]] = start_index
if A[start_index] in S1:
S1.remove(A[start_index])
start_index += 1
if start_index == N:
break
until_here = min(last_seen)
num_ending_before = [(1) for _ in range(start_index)]
if start_index <= end_index + 1:
num_ending_before += [2]
for i in range(start_index, end_index + 1):
if A[i] < MEX:
last_seen[A[i]] = i
while True:
if A[until_here] >= MEX:
until_here += 1
elif last_seen[A[until_here]] > until_here:
until_here += 1
else:
break
num_ending_before += [
(num_ending_before[until_here] + num_ending_before[-1]) % P
]
print(num_ending_before[-1]) | ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER WHILE NUMBER IF VAR VAR VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER WHILE NUMBER IF VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR WHILE NUMBER IF VAR IF VAR VAR VAR ASSIGN VAR VAR VAR VAR IF VAR VAR VAR EXPR FUNC_CALL VAR VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR NUMBER VAR LIST NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR VAR VAR WHILE NUMBER IF VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR VAR NUMBER VAR LIST BIN_OP BIN_OP VAR VAR VAR NUMBER VAR EXPR FUNC_CALL VAR VAR NUMBER |
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Ridbit is given an array $a_{1}, a_{2}, \ldots, a_{N}$. He needs to find the number of ways to divide the array into contiguous subarrays such that:
Each element of the sequence $a$ belongs to exactly one of the subarrays.
There is an integer $m$ such that the MEX of every subarray is equal to $m$. The MEX of a sequence is the smallest non-negative integer which does not occur in this sequence.
Help Ridbit with this task.
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first line of each test case contains a single integer $N$.
The second line contains $N$ space-separated integers $a_{1}, a_{2}, \ldots, a_{N}$.
------ Output ------
For each test case, print a single line containing one integer ― the number of ways to divide the sequence, modulo $10^{9} + 7$.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 100,000$
$0 ≤ a_{i} ≤ N$ for each valid $i$
----- Sample Input 1 ------
2
6
1 0 0 1 0 1
3
1 2 3
----- Sample Output 1 ------
5
4
----- explanation 1 ------
Example case 1: The five valid ways to divide the sequence are:
- $[1, 0, 0, 1, 0, 1]$
- $[1, 0], [0, 1, 0, 1]$
- $[1, 0, 0], [1, 0, 1]$
- $[1, 0, 0, 1], [0, 1]$
- $[1, 0], [0, 1], [0, 1]$ | from sys import stdin
input = stdin.readline
mod = 10**9 + 7
def add(a, b):
return (a % mod + b % mod) % mod
def mexofa():
c = [0] * (size + 1)
for i in a:
c[i] += 1
for i in range(size + 1):
if c[i] == 0:
return i
def answer():
if mex == 0:
return pow(2, n - 1, mod)
c = [0] * (size + 1)
nextind = [-1] * n
m = 0
for i in range(n - 1, -1, -1):
if a[i] == m:
for j in range(a[i] + 1, size + 1):
if c[j] == 0:
m = j
break
c[a[i]] += 1
if m == mex:
nextind[n - 1] = i
break
need = -1
for i in range(n - 2, -1, -1):
c[a[i + 1]] -= 1
if c[a[i + 1]] == 0 and a[i + 1] < mex:
need = a[i + 1]
if need == -1:
nextind[i] = nextind[i + 1]
continue
for j in range(nextind[i + 1] - 1, -1, -1):
c[a[j]] += 1
if need == a[j]:
nextind[i] = j
break
need = -1
dp = [0] * (n + 1)
pf = [0] * (n + 1)
for i in range(1, n + 1):
if nextind[i - 1] == -1:
continue
dp[i] = add(dp[i], pf[nextind[i - 1]] + 1)
pf[i] = add(pf[i], dp[i])
pf[i] = add(pf[i], pf[i - 1])
return dp[n]
for T in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
size = max(a) + 1
mex = mexofa()
print(answer()) | ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FUNC_DEF RETURN BIN_OP BIN_OP BIN_OP VAR VAR BIN_OP VAR VAR VAR FUNC_DEF ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR NUMBER RETURN VAR FUNC_DEF IF VAR NUMBER RETURN FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR NUMBER IF VAR VAR ASSIGN VAR BIN_OP VAR NUMBER VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER VAR VAR BIN_OP VAR NUMBER NUMBER IF VAR VAR BIN_OP VAR NUMBER NUMBER VAR BIN_OP VAR NUMBER VAR ASSIGN VAR VAR BIN_OP VAR NUMBER IF VAR NUMBER ASSIGN VAR VAR VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR BIN_OP VAR NUMBER NUMBER NUMBER NUMBER VAR VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR VAR ASSIGN VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR VAR BIN_OP VAR NUMBER NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR NUMBER 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 BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR EXPR FUNC_CALL VAR FUNC_CALL VAR |
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Ridbit is given an array $a_{1}, a_{2}, \ldots, a_{N}$. He needs to find the number of ways to divide the array into contiguous subarrays such that:
Each element of the sequence $a$ belongs to exactly one of the subarrays.
There is an integer $m$ such that the MEX of every subarray is equal to $m$. The MEX of a sequence is the smallest non-negative integer which does not occur in this sequence.
Help Ridbit with this task.
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first line of each test case contains a single integer $N$.
The second line contains $N$ space-separated integers $a_{1}, a_{2}, \ldots, a_{N}$.
------ Output ------
For each test case, print a single line containing one integer ― the number of ways to divide the sequence, modulo $10^{9} + 7$.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 100,000$
$0 ≤ a_{i} ≤ N$ for each valid $i$
----- Sample Input 1 ------
2
6
1 0 0 1 0 1
3
1 2 3
----- Sample Output 1 ------
5
4
----- explanation 1 ------
Example case 1: The five valid ways to divide the sequence are:
- $[1, 0, 0, 1, 0, 1]$
- $[1, 0], [0, 1, 0, 1]$
- $[1, 0, 0], [1, 0, 1]$
- $[1, 0, 0, 1], [0, 1]$
- $[1, 0], [0, 1], [0, 1]$ | import sys
T = int(input())
P = 1000000007
for t in range(T):
N = int(input())
A = list(int(x) for x in sys.stdin.readline().split())
m1 = min(A)
if m1 > 0:
print(pow(2, N - 1, P))
else:
nums = [0] * 100001
for a in A:
nums[a] += 1
mex = -1
for i in range(len(nums)):
if nums[i] == 0:
mex = i
break
T = []
mymap = [0] * mex
cnt = 0
j = 0
while j < N and cnt < mex:
val = A[j]
if val < mex:
if mymap[val] == 0:
cnt += 1
mymap[val] += 1
j += 1
if cnt == mex:
T.append(1)
break
else:
T.append(0)
if j == N:
if cnt == mex:
print(1)
else:
print(0)
else:
setStart = 0
while j < N:
while cnt == mex:
val = A[setStart]
if val < mex:
mymap[val] -= 1
if mymap[val] == 0:
cnt -= 1
setStart += 1
val = A[j]
if val < mex:
if mymap[val] == 0:
cnt += 1
mymap[val] += 1
newval = T[-1]
if cnt == mex:
newval += T[setStart - 1]
newval = newval % P
while (
A[setStart] < mex
and mymap[A[setStart]] > 1
or A[setStart] > mex
):
if A[setStart] > mex:
setStart += 1
newval += T[setStart - 1]
newval = newval % P
else:
mymap[A[setStart]] -= 1
setStart += 1
newval += T[setStart - 1]
newval = newval % P
T.append(newval)
j += 1
2
print(T[-1]) | IMPORT ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR VAR FUNC_CALL FUNC_CALL VAR ASSIGN VAR FUNC_CALL VAR VAR IF VAR NUMBER EXPR FUNC_CALL VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER NUMBER FOR VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR LIST ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR VAR VAR ASSIGN VAR VAR VAR IF VAR VAR IF VAR VAR NUMBER VAR NUMBER VAR VAR NUMBER VAR NUMBER IF VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR NUMBER IF VAR VAR IF VAR VAR EXPR FUNC_CALL VAR NUMBER EXPR FUNC_CALL VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR WHILE VAR VAR ASSIGN VAR VAR VAR IF VAR VAR VAR VAR NUMBER IF VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR IF VAR VAR NUMBER VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR NUMBER IF VAR VAR VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR VAR WHILE VAR VAR VAR VAR VAR VAR NUMBER VAR VAR VAR IF VAR VAR VAR VAR NUMBER VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR NUMBER VAR NUMBER VAR VAR BIN_OP VAR NUMBER ASSIGN VAR BIN_OP VAR VAR EXPR FUNC_CALL VAR VAR VAR NUMBER EXPR NUMBER EXPR FUNC_CALL VAR VAR NUMBER |
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Ridbit is given an array $a_{1}, a_{2}, \ldots, a_{N}$. He needs to find the number of ways to divide the array into contiguous subarrays such that:
Each element of the sequence $a$ belongs to exactly one of the subarrays.
There is an integer $m$ such that the MEX of every subarray is equal to $m$. The MEX of a sequence is the smallest non-negative integer which does not occur in this sequence.
Help Ridbit with this task.
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first line of each test case contains a single integer $N$.
The second line contains $N$ space-separated integers $a_{1}, a_{2}, \ldots, a_{N}$.
------ Output ------
For each test case, print a single line containing one integer ― the number of ways to divide the sequence, modulo $10^{9} + 7$.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 100,000$
$0 ≤ a_{i} ≤ N$ for each valid $i$
----- Sample Input 1 ------
2
6
1 0 0 1 0 1
3
1 2 3
----- Sample Output 1 ------
5
4
----- explanation 1 ------
Example case 1: The five valid ways to divide the sequence are:
- $[1, 0, 0, 1, 0, 1]$
- $[1, 0], [0, 1, 0, 1]$
- $[1, 0, 0], [1, 0, 1]$
- $[1, 0, 0, 1], [0, 1]$
- $[1, 0], [0, 1], [0, 1]$ | def find_mex(arr):
max_value = len(arr) + 1
all_possibles = set(range(max_value))
arr_values = set(arr)
omissions = all_possibles - arr_values
return min(omissions)
def calc_k(arr, mex):
DP = [None] * (len(arr) + 1)
for i in range(len(arr) + 1):
if mex:
DP[i] = [0, 0, 0]
else:
DP[i] = [1, 0, 0]
end_pointer = 0
start_pointer = 0
counts = {i: (0) for i in range(mex)}
missing_numbers = set([i for i in range(mex)])
while end_pointer < len(arr):
if arr[end_pointer] < mex:
counts[arr[end_pointer]] += 1
if counts[arr[end_pointer]] == 1:
missing_numbers.remove(arr[end_pointer])
while not missing_numbers:
DP[start_pointer][0] = end_pointer - start_pointer + 1
if arr[start_pointer] < mex:
counts[arr[start_pointer]] -= 1
if counts[arr[start_pointer]] == 0:
missing_numbers.add(arr[start_pointer])
start_pointer += 1
end_pointer += 1
return DP
def calc_DP(DP):
M = 10**9 + 7
for i in range(len(arr) - 1, -1, -1):
if testing:
print(i, DP[i], end="")
if DP[i][0]:
k = DP[i][0]
DP[i][1] = (1 + DP[i + k][2]) % M
DP[i][2] = (DP[i][1] + DP[i + 1][2]) % M
if testing:
print("->", DP[i])
elif testing:
print()
return DP
testing = False
if testing:
arr = [1, 0, 0, 1, 0, 1]
mex = find_mex(arr)
print(arr, mex)
DP = calc_k(arr, mex)
print(DP)
print(calc_DP(DP))
arr = [1, 2, 3]
mex = find_mex(arr)
print(arr, mex)
DP = calc_k(arr, mex)
print(DP)
print(calc_DP(DP))
T = int(input())
for tc in range(T):
N = int(input())
arr = [int(x) for x in input().strip().split(" ")]
mex = find_mex(arr)
DP = DP = calc_k(arr, mex)
print(calc_DP(DP)[0][1]) | FUNC_DEF ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR VAR RETURN FUNC_CALL VAR VAR FUNC_DEF ASSIGN VAR BIN_OP LIST NONE BIN_OP FUNC_CALL VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER IF VAR ASSIGN VAR VAR LIST NUMBER NUMBER NUMBER ASSIGN VAR VAR LIST NUMBER NUMBER NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR WHILE VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR WHILE VAR ASSIGN VAR VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR NUMBER EXPR FUNC_CALL VAR VAR VAR VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER NUMBER NUMBER IF VAR EXPR FUNC_CALL VAR VAR VAR VAR STRING IF VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR NUMBER BIN_OP BIN_OP NUMBER VAR BIN_OP VAR VAR NUMBER VAR ASSIGN VAR VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER VAR BIN_OP VAR NUMBER NUMBER VAR IF VAR EXPR FUNC_CALL VAR STRING VAR VAR IF VAR EXPR FUNC_CALL VAR RETURN VAR ASSIGN VAR NUMBER IF VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR LIST NUMBER NUMBER NUMBER ASSIGN VAR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL 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 VAR VAR FUNC_CALL FUNC_CALL FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR VAR NUMBER NUMBER |
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese], and [Bengali] as well.
Ridbit is given an array $a_{1}, a_{2}, \ldots, a_{N}$. He needs to find the number of ways to divide the array into contiguous subarrays such that:
Each element of the sequence $a$ belongs to exactly one of the subarrays.
There is an integer $m$ such that the MEX of every subarray is equal to $m$. The MEX of a sequence is the smallest non-negative integer which does not occur in this sequence.
Help Ridbit with this task.
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first line of each test case contains a single integer $N$.
The second line contains $N$ space-separated integers $a_{1}, a_{2}, \ldots, a_{N}$.
------ Output ------
For each test case, print a single line containing one integer ― the number of ways to divide the sequence, modulo $10^{9} + 7$.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 100,000$
$0 ≤ a_{i} ≤ N$ for each valid $i$
----- Sample Input 1 ------
2
6
1 0 0 1 0 1
3
1 2 3
----- Sample Output 1 ------
5
4
----- explanation 1 ------
Example case 1: The five valid ways to divide the sequence are:
- $[1, 0, 0, 1, 0, 1]$
- $[1, 0], [0, 1, 0, 1]$
- $[1, 0, 0], [1, 0, 1]$
- $[1, 0, 0, 1], [0, 1]$
- $[1, 0], [0, 1], [0, 1]$ | def main():
mod = 10**9 + 7
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
xx = [0] * (n + 2)
for i in a:
xx[i] += 1
if min(a):
print(pow(2, n - 1, mod))
continue
for i in range(n + 2):
if not xx[i]:
m = i
break
req = [0] * m
done = m
dp = [-1] * n
i = n - 1
for j in range(n - 1, -1, -1):
if a[j] < len(req):
req[a[j]] += 1
if req[a[j]] == 1:
done -= 1
while i != -1 and not done:
dp[i] = j
if a[i] < len(req):
req[a[i]] -= 1
done += req[a[i]] == 0
i -= 1
dp1 = [0] * n
pref = [1] + [0] * n
for i in range(n):
if dp[i] != -1:
dp1[i] = pref[dp[i]]
pref[i + 1] = (pref[i] + dp1[i]) % mod
print(dp1[-1])
main() | FUNC_DEF ASSIGN VAR BIN_OP BIN_OP NUMBER NUMBER NUMBER 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 LIST NUMBER BIN_OP VAR NUMBER FOR VAR VAR VAR VAR NUMBER IF FUNC_CALL VAR VAR EXPR FUNC_CALL VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER NUMBER NUMBER IF VAR VAR FUNC_CALL VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR NUMBER VAR NUMBER WHILE VAR NUMBER VAR ASSIGN VAR VAR VAR IF VAR VAR FUNC_CALL VAR VAR VAR VAR VAR NUMBER VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR BIN_OP LIST NUMBER VAR ASSIGN VAR BIN_OP LIST NUMBER BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR VAR IF VAR VAR NUMBER ASSIGN VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR NUMBER BIN_OP BIN_OP VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR NUMBER EXPR FUNC_CALL VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
res = set()
mem = [[(0) for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n - 1):
mem[i][preferences[i][j]] = j + 1
for i in range(n // 2):
x = pairs[i][0]
y = pairs[i][1]
for j in range(i + 1, n // 2):
u = pairs[j][0]
v = pairs[j][1]
if mem[x][u] < mem[x][y] and mem[u][x] < mem[u][v]:
res.add(x)
res.add(u)
if mem[x][v] < mem[x][y] and mem[v][x] < mem[v][u]:
res.add(x)
res.add(v)
if mem[y][u] < mem[y][x] and mem[u][y] < mem[u][v]:
res.add(y)
res.add(u)
if mem[y][v] < mem[y][x] and mem[v][y] < mem[v][u]:
res.add(y)
res.add(v)
return len(res) | CLASS_DEF FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR VAR NUMBER ASSIGN VAR VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
idx_table = collections.defaultdict(lambda: collections.defaultdict(int))
for i in range(n):
for idx, person in enumerate(preferences[i]):
idx_table[i][person] = idx
unhappy = [0] * n
for i in range(n // 2):
a, b = pairs[i]
b_a_idx, a_b_idx = idx_table[b][a], idx_table[a][b]
for j in range(i + 1, n // 2):
c, d = pairs[j]
c_a_idx = idx_table[c][a]
c_b_idx = idx_table[c][b]
c_d_idx = idx_table[c][d]
d_a_idx = idx_table[d][a]
d_b_idx = idx_table[d][b]
d_c_idx = idx_table[d][c]
a_c_idx = idx_table[a][c]
a_d_idx = idx_table[a][d]
b_c_idx = idx_table[b][c]
b_d_idx = idx_table[b][d]
if c_a_idx < c_d_idx and a_c_idx < a_b_idx:
unhappy[a] = unhappy[c] = 1
if d_a_idx < d_c_idx and a_d_idx < a_b_idx:
unhappy[a] = unhappy[d] = 1
if c_b_idx < c_d_idx and b_c_idx < b_a_idx:
unhappy[b] = unhappy[c] = 1
if d_b_idx < d_c_idx and b_d_idx < b_a_idx:
unhappy[b] = unhappy[d] = 1
return sum(unhappy) | CLASS_DEF FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
unhappy = [0] * n
for i in range(n // 2):
a, b = pairs[i]
b_a_idx, a_b_idx = preferences[b].index(a), preferences[a].index(b)
for j in range(i + 1, n // 2):
c, d = pairs[j]
c_a_idx = preferences[c].index(a)
c_b_idx = preferences[c].index(b)
c_d_idx = preferences[c].index(d)
d_a_idx = preferences[d].index(a)
d_b_idx = preferences[d].index(b)
d_c_idx = preferences[d].index(c)
a_c_idx = preferences[a].index(c)
a_d_idx = preferences[a].index(d)
b_c_idx = preferences[b].index(c)
b_d_idx = preferences[b].index(d)
if c_a_idx < c_d_idx and a_c_idx < a_b_idx:
unhappy[a] = unhappy[c] = 1
if d_a_idx < d_c_idx and a_d_idx < a_b_idx:
unhappy[a] = unhappy[d] = 1
if c_b_idx < c_d_idx and b_c_idx < b_a_idx:
unhappy[b] = unhappy[c] = 1
if d_b_idx < d_c_idx and b_d_idx < b_a_idx:
unhappy[b] = unhappy[d] = 1
return sum(unhappy) | CLASS_DEF FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR BIN_OP LIST NUMBER VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER RETURN FUNC_CALL VAR VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def get_pair(self, i):
for j in self.pairs:
if i in j:
for k in j:
if k != i:
return k
def t_happy(self, t, i):
pair = self.get_pair(t)
for j in self.prefer[t]:
if j == pair:
return True
if j == i:
return False
def happy(self, i, p):
prefer = self.prefer[i]
if prefer[0] == p:
return True
for j in range(1, len(prefer)):
if not self.t_happy(prefer[j - 1], i):
return False
if prefer[j] == p:
return True
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
self.prefer = preferences
self.pairs = pairs
count = 0
for i in range(n):
p = self.get_pair(i)
if not self.happy(i, p):
count += 1
return count | CLASS_DEF FUNC_DEF FOR VAR VAR IF VAR VAR FOR VAR VAR IF VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR FOR VAR VAR VAR IF VAR VAR RETURN NUMBER IF VAR VAR RETURN NUMBER FUNC_DEF ASSIGN VAR VAR VAR IF VAR NUMBER VAR RETURN NUMBER FOR VAR FUNC_CALL VAR NUMBER FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR BIN_OP VAR NUMBER VAR RETURN NUMBER IF VAR VAR VAR RETURN NUMBER FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR IF FUNC_CALL VAR VAR VAR VAR NUMBER RETURN VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
pref = {}
for i in range(len(preferences)):
pref[i] = {}
plist = preferences[i]
for j in range(len(plist)):
pref[i][plist[j]] = j
print(pref)
unhappy = set()
for i in range(len(pairs)):
for j in range(len(pairs)):
if i == j:
continue
for x in pairs[i]:
y = pairs[i][1] if x == pairs[i][0] else pairs[i][0]
for u in pairs[j]:
v = pairs[j][1] if u == pairs[j][0] else pairs[j][0]
if pref[x][y] > pref[x][u] and pref[u][v] > pref[u][x]:
unhappy.add(x)
return len(unhappy) | CLASS_DEF FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR DICT FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR DICT ASSIGN VAR VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR VAR FOR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER FOR VAR VAR VAR ASSIGN VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
preference_list = [[(0) for _ in range(n)] for _ in range(n)]
for x in range(n):
for i, y in enumerate(preferences[x]):
preference_list[x][y] = n - i - 1
unhappy = {}
for i in range(n // 2):
x, y = pairs[i]
for j in range(n // 2):
u, v = pairs[j]
if i != j:
if (
preference_list[x][y] < preference_list[x][u]
and preference_list[u][x] > preference_list[u][v]
or preference_list[x][y] < preference_list[x][v]
and preference_list[v][u] < preference_list[v][x]
):
unhappy[x] = 1
if (
preference_list[y][x] < preference_list[y][u]
and preference_list[u][y] > preference_list[u][v]
or preference_list[y][x] < preference_list[y][v]
and preference_list[v][u] < preference_list[v][y]
):
unhappy[y] = 1
res = len(unhappy)
return res | CLASS_DEF FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR NUMBER VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR DICT FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR IF VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR RETURN VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def unhappyFriends(self, n: int, P: List[List[int]], A: List[List[int]]) -> int:
unhappy = set()
for i in range(n // 2):
for j in range(i + 1, n // 2):
Ai0, Ai1, Aj0, Aj1 = A[i][0], A[i][1], A[j][0], A[j][1]
if P[Ai0].index(Ai1) > P[Ai0].index(Aj0) and P[Aj0].index(Aj1) > P[
Aj0
].index(Ai0):
unhappy.add(Ai0)
unhappy.add(Aj0)
Ai0, Ai1, Aj0, Aj1 = A[i][1], A[i][0], A[j][0], A[j][1]
if P[Ai0].index(Ai1) > P[Ai0].index(Aj0) and P[Aj0].index(Aj1) > P[
Aj0
].index(Ai0):
unhappy.add(Ai0)
unhappy.add(Aj0)
Ai0, Ai1, Aj0, Aj1 = A[i][0], A[i][1], A[j][1], A[j][0]
if P[Ai0].index(Ai1) > P[Ai0].index(Aj0) and P[Aj0].index(Aj1) > P[
Aj0
].index(Ai0):
unhappy.add(Ai0)
unhappy.add(Aj0)
Ai0, Ai1, Aj0, Aj1 = A[i][1], A[i][0], A[j][1], A[j][0]
if P[Ai0].index(Ai1) > P[Ai0].index(Aj0) and P[Aj0].index(Aj1) > P[
Aj0
].index(Ai0):
unhappy.add(Ai0)
unhappy.add(Aj0)
return len(unhappy) | CLASS_DEF FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER BIN_OP VAR NUMBER ASSIGN VAR VAR VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER VAR VAR NUMBER IF FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN FUNC_CALL VAR VAR VAR |
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:
x prefers u over y, and
u prefers x over v.
Return the number of unhappy friends.
Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.
Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4
Constraints:
2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair. | class Solution:
def preferences_to_scores(self, preferences):
scores = {}
for u, up in enumerate(preferences):
for s, v in enumerate(up):
scores[u, v] = s
return scores
def unhappy_friends(self, scores, a, b):
ret = set()
for ai, aa in enumerate(a):
af = a[1 - ai]
for bi, bb in enumerate(b):
bf = b[1 - bi]
if scores[aa, bb] < scores[aa, af] and scores[bb, aa] < scores[bb, bf]:
ret.add(aa)
ret.add(bb)
return ret
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
scores = self.preferences_to_scores(preferences)
ret = set()
for i, a in enumerate(pairs):
for j in range(i):
b = pairs[j]
ret |= self.unhappy_friends(scores, a, b)
return len(ret) | CLASS_DEF FUNC_DEF ASSIGN VAR DICT FOR VAR VAR FUNC_CALL VAR VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR BIN_OP NUMBER VAR FOR VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR BIN_OP NUMBER VAR IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR EXPR FUNC_CALL VAR VAR EXPR FUNC_CALL VAR VAR RETURN VAR FUNC_DEF VAR VAR VAR VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR FOR VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR VAR FUNC_CALL VAR VAR VAR VAR RETURN FUNC_CALL VAR VAR VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def palindrome(self, a, b, st, end):
i = 0
j = len(a) - 1
i2 = 0
j2 = len(b) - 1
op = 0
while i < j:
if i < st and j > end or j < st or i > end:
if a[i] != a[j]:
op += 1
elif j > end:
if b[i2] != a[j]:
op += 1
i2 += 1
elif i < st:
if a[i] != b[j2]:
op += 1
j2 -= 1
else:
if b[i2] != b[j2]:
return 99999
i2 += 1
j2 -= 1
i += 1
j -= 1
return op
def specialPalindrome(self, a, b):
ans = 99999
for i in range(len(a) - len(b) + 1):
st = i
end = i + len(b) - 1
temp = 0
k = 0
for j in range(st, end + 1):
if a[j] != b[k]:
temp += 1
k += 1
t = self.palindrome(a, b, st, end)
if t == ans:
temp = t
else:
temp += t
ans = min(ans, temp)
if ans == 99999:
return -1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR IF VAR VAR VAR VAR VAR NUMBER IF VAR VAR IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER IF VAR VAR IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER IF VAR VAR VAR VAR RETURN NUMBER VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR NUMBER IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR VAR IF VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR NUMBER RETURN NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
makeP = 0
i, j = 0, len(s1) - 1
dic = {}
while i <= j:
if s1[i] != s1[j]:
makeP += 1
dic[i] = s1[i]
dic[j] = s1[j]
i += 1
j -= 1
def check(string, i, pat):
score = 0
aldy = {}
j = 0
while j < len(pat):
if i in aldy:
if pat[j] != aldy[i]:
return False, 0
elif i not in dic:
aldy[i] = pat[j]
aldy[len(s1) - i - 1] = pat[j]
if string[i] != pat[j]:
if i != len(s1) - i - 1:
score += 2
else:
score += 1
else:
c1 = string[i]
c2 = string[len(s1) - i - 1]
if pat[j] != c1 and pat[j] != c2:
score += 1
aldy[i] = pat[j]
aldy[len(s1) - i - 1] = pat[j]
i += 1
j += 1
return True, score
minimum = float("inf")
for i in range(len(s1) - len(s2) + 1):
isposs, s = check(s1, i, s2)
if isposs:
minimum = min(minimum, s)
ans = makeP + minimum
return ans if ans != float("inf") else -1 | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR DICT WHILE VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR VAR NUMBER VAR NUMBER FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR DICT ASSIGN VAR NUMBER WHILE VAR FUNC_CALL VAR VAR IF VAR VAR IF VAR VAR VAR VAR RETURN NUMBER NUMBER IF VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER VAR VAR IF VAR VAR VAR VAR IF VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR ASSIGN VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER IF VAR VAR VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER VAR VAR VAR NUMBER VAR NUMBER RETURN NUMBER VAR ASSIGN VAR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR VAR VAR IF VAR ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR RETURN VAR FUNC_CALL VAR STRING VAR NUMBER |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s, t):
def makePalindrome(s, l, h):
i, j = 0, len(s) - 1
cnt = 0
while i < j:
if i >= l and i <= h and j <= h and j >= l and s[i] != s[j]:
return float("inf")
if s[i] != s[j]:
cnt += 1
i += 1
j -= 1
return cnt
mini = float("inf")
n, m = len(s), len(t)
for i in range(0, n - m + 1):
temp = s[:i] + t + s[i + m :]
cnt = 0
for j in range(m):
if s[i + j] != t[j]:
cnt += 1
mini = min(mini, makePalindrome(temp, i, i + m - 1) + cnt)
return -1 if mini == float("inf") else mini | CLASS_DEF FUNC_DEF FUNC_DEF ASSIGN VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR VAR RETURN FUNC_CALL VAR STRING IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER VAR RETURN VAR FUNC_CALL VAR STRING NUMBER VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
mud = 0
menor = 1000
a = 0
for i in range(len(s1) - len(s2) + 1):
s3 = s1[:i] + s2 + s1[i + len(s2) :]
for y in range(i, i + len(s2)):
k = len(s3) - 1 - y
if s3[y] != s3[k] and k >= i and k < len(s2) + i:
a = 1
break
if s3[y] != s1[y]:
mud += 1
if a == 0:
for p in range(len(s3) // 2):
if s3[p] != s3[len(s3) - p - 1]:
mud += 1
if mud < menor:
menor = mud
mud = 0
a = 0
if menor == 1000:
return -1
return menor | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER VAR IF VAR VAR VAR VAR VAR VAR VAR BIN_OP FUNC_CALL VAR VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR VAR VAR NUMBER IF VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER IF VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER RETURN NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | import sys
def f(a, b, strt, end):
ans = 0
i = 0
j = len(a) - 1
while i <= j:
if i >= strt and i <= end:
if j >= strt and j <= end:
if b[i - strt] != b[j - strt]:
return -1
if a[i] != b[i - strt]:
ans += 1
if a[j] != b[j - strt] and i != j:
ans += 1
else:
if a[i] != b[i - strt]:
ans += 1
if b[i - strt] != a[j] and i != j:
ans += 1
elif j >= strt and j <= end:
if a[j] != b[j - strt]:
ans += 1
if b[j - strt] != a[i] and i != j:
ans += 1
elif a[i] != a[j]:
ans += 1
i += 1
j -= 1
return ans
class Solution:
def specialPalindrome(self, s1, s2):
ans = sys.maxsize
for i in range(0, len(s1) - len(s2) + 1):
val = f(s1, s2, i, i + len(s2) - 1)
if val != -1:
ans = min(ans, val)
if ans == sys.maxsize:
ans = -1
return ans | IMPORT FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR IF VAR VAR VAR VAR IF VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR RETURN NUMBER IF VAR VAR VAR BIN_OP VAR VAR VAR NUMBER IF VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR BIN_OP VAR VAR VAR NUMBER IF VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR IF VAR VAR VAR BIN_OP VAR VAR VAR NUMBER IF VAR BIN_OP VAR VAR VAR VAR VAR VAR VAR NUMBER IF VAR VAR VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR CLASS_DEF FUNC_DEF ASSIGN VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR VAR BIN_OP BIN_OP VAR FUNC_CALL VAR VAR NUMBER IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR VAR ASSIGN VAR NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
s1l = len(s1)
s2l = len(s2)
ans = float("inf")
if s1l < s2l:
return -1
for i in range(s1l - s2l + 1):
temp = s1[:i] + s2 + s1[i + s2l :]
cost = 0
for j in range(i, i + s2l):
if temp[j] != s1[j]:
cost += 1
flag = True
for j in range(s1l // 2):
if (i > j or j >= i + s2l) and temp[j] != temp[s1l - j - 1]:
cost += 1
elif (s1l - i - s2l - 1 >= j or s1l - i - 1 < j) and temp[j] != temp[
s1l - j - 1
]:
cost += 1
elif temp[j] != temp[s1l - j - 1]:
flag = False
break
if flag == True:
ans = min(ans, cost)
if ans == float("inf"):
return -1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR STRING IF VAR VAR RETURN NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP VAR VAR VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER VAR NUMBER IF BIN_OP BIN_OP BIN_OP VAR VAR VAR NUMBER VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR FUNC_CALL VAR STRING RETURN NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(sefl, s1, s2):
costs = []
for i in range(0, len(s1) - len(s2) + 1):
s3 = s1[0:i] + s2 + s1[i + len(s2) :]
cost = 0
for j in range(i, i + len(s2)):
if s1[j] != s3[j]:
cost += 1
pcost = 0
for k in range(0, len(s3) // 2):
if s3[k] != s3[-(k + 1)]:
if i <= k <= i + len(s2) and i <= len(s3) - k <= i + len(s2):
pcost = -1
break
elif i <= k <= i + len(s2):
pcost += 1
elif i <= len(s1) - k <= i + len(s2):
pcost += 1
else:
pcost += 1
if pcost >= 0:
costs.append(cost + pcost)
min_cost = sorted(costs)[0] if costs else -1
return min_cost | CLASS_DEF FUNC_DEF ASSIGN VAR LIST FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR BIN_OP VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER IF VAR VAR VAR BIN_OP VAR NUMBER IF VAR VAR BIN_OP VAR FUNC_CALL VAR VAR VAR BIN_OP FUNC_CALL VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER IF VAR VAR BIN_OP VAR FUNC_CALL VAR VAR VAR NUMBER IF VAR BIN_OP FUNC_CALL VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR VAR NUMBER VAR NUMBER IF VAR NUMBER EXPR FUNC_CALL VAR BIN_OP VAR VAR ASSIGN VAR VAR FUNC_CALL VAR VAR NUMBER NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
a = 1
for _ in range(1000):
a += 1
s1 = [c for c in s1]
s2 = [c for c in s2]
ans = float("inf")
for i in range(0, len(s1) - len(s2) + 1):
s = s1[:]
count = 0
for j in range(len(s2)):
if s1[i + j] != s2[j]:
s[i + j] = s2[j]
count += 1
left = 0
right = len(s1) - 1
f = True
while left < right:
if s[left] != s[right]:
if i <= left < i + len(s2) and i <= right < i + len(s2):
f = False
break
count += 1
left += 1
right -= 1
if f:
ans = min(ans, count)
if ans == float("inf"):
return -1
return ans | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER VAR NUMBER ASSIGN VAR VAR VAR VAR ASSIGN VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR IF VAR VAR BIN_OP VAR FUNC_CALL VAR VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER VAR NUMBER VAR NUMBER VAR NUMBER IF VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR FUNC_CALL VAR STRING RETURN NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
n, m = len(s1), len(s2)
org = list(s1)
slis = org[:]
res = 100000000.0
for i in range(n - m + 1):
cur = 0
for j in range(m):
if slis[i + j] != s2[j]:
slis[i + j] = s2[j]
cur += 1
cr = range(i, i + m)
for x in range(n // 2):
if slis[x] != slis[n - x - 1]:
if x in cr and n - x - 1 in cr:
break
else:
cur += 1
else:
res = min(res, cur)
slis = org[:]
return res if res < 100000000.0 else -1 | CLASS_DEF FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR BIN_OP VAR VAR FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR ASSIGN VAR VAR RETURN VAR NUMBER VAR NUMBER |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
if len(s2) > len(s1):
return -1
if s2 in s1:
count = 0
for j in range(0, l1 // 2):
if s1[j] != s1[l1 - 1 - j]:
count += 1
return count
else:
l2 = len(s2)
l1 = len(s1)
l2_poli = True
for j in range(0, l2 // 2):
if s2[j] != s2[l2 - 1 - j]:
l2_poli = False
break
ans = -1
for i in range(len(s1) + 1 - len(s2)):
count = l2 - sum(x == y for x, y in zip(s1[i : i + len(s2)], s2))
s1_temp = s1[:i] + s2 + s1[i + len(s2) :]
for j in range(0, l1 // 2):
if s1_temp[j] != s1_temp[l1 - 1 - j]:
if j >= i and l1 - 1 - j <= i + len(s2) - 1:
count = -1
break
count += 1
if ans != -1:
ans = min(ans, count if count != -1 else ans)
else:
ans = count if count != -1 else -1
return ans | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR FUNC_CALL VAR VAR RETURN NUMBER IF VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP VAR NUMBER VAR VAR NUMBER RETURN VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP VAR NUMBER VAR ASSIGN VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR FUNC_CALL VAR VAR VAR VAR VAR FUNC_CALL VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR VAR VAR BIN_OP VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR NUMBER BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP VAR NUMBER VAR IF VAR VAR BIN_OP BIN_OP VAR NUMBER VAR BIN_OP BIN_OP VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER VAR NUMBER IF VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR NUMBER VAR VAR ASSIGN VAR VAR NUMBER VAR NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def palop1(self, temp, i, m):
low = 0
high = len(temp) - 1
pal = 0
while low <= high:
if temp[low] != temp[high]:
if low >= i and high <= i + m - 1:
return 1000000000.0
pal += 1
low += 1
high -= 1
return pal
def specialPalindrome(self, s1, s2):
n = len(s1)
m = len(s2)
mini = 1000000000.0
for i in range(n - m + 1):
temp = list(s1)
op = 0
for j in range(m):
if temp[i + j] != s2[j]:
op += 1
temp[i + j] = s2[j]
op = op + self.palop1(temp, i, m)
mini = min(mini, op)
if mini == 1000000000.0:
return -1
return mini | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR IF VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN NUMBER VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR IF VAR NUMBER RETURN NUMBER RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
n1, n2 = len(s1), len(s2)
ans = float("inf")
for i in range(n1 - n2 + 1):
costs = 0
for k in range(n2):
if s1[i + k] != s2[k]:
costs += 1
j1, j2 = 0, n1 - 1
while j1 < j2:
if i <= j1 < i + n2 and i <= j2 < i + n2 and s2[j1 - i] != s2[j2 - i]:
break
left = s1[j1]
if i <= j1 < i + n2:
left = s2[j1 - i]
right = s1[j2]
if i <= j2 < i + n2:
right = s2[j2 - i]
if left != right:
costs += 1
j1 += 1
j2 -= 1
else:
ans = min(ans, costs)
return -1 if ans == float("inf") else ans | CLASS_DEF FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR STRING FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR VAR NUMBER BIN_OP VAR NUMBER WHILE VAR VAR IF VAR VAR BIN_OP VAR VAR VAR VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR IF VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR IF VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR IF VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_CALL VAR STRING NUMBER VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
def get(k):
return (s2[k - i], True) if i <= k < i + N2 else (s1[k], False)
Inv, N1, N2 = 10**9, len(s1), len(s2)
ans, baseline = Inv, 0
for i in range(N1 // 2):
if s1[i] != s1[N1 - 1 - i]:
baseline += 1
for i in range(N1 - N2 + 1):
tmp = baseline
for j in range(i, i + N2):
c0, (c1, f1) = s2[j - i], get(N1 - 1 - j)
if s1[j] != s1[N1 - 1 - j] and (not f1 or j < N1 - 1 - j):
tmp -= 1
if c0 != s1[j]:
tmp += 1
if c0 != c1:
if f1:
tmp = Inv
break
tmp += 1
ans = min(ans, tmp)
return -1 if ans >= Inv else ans | CLASS_DEF FUNC_DEF FUNC_DEF RETURN VAR VAR BIN_OP VAR VAR VAR BIN_OP VAR VAR NUMBER VAR VAR NUMBER ASSIGN VAR VAR VAR BIN_OP NUMBER NUMBER FUNC_CALL VAR VAR FUNC_CALL VAR VAR ASSIGN VAR VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP VAR NUMBER IF VAR VAR VAR BIN_OP BIN_OP VAR NUMBER VAR VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR VAR BIN_OP VAR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR NUMBER VAR IF VAR VAR VAR BIN_OP BIN_OP VAR NUMBER VAR VAR VAR BIN_OP BIN_OP VAR NUMBER VAR VAR NUMBER IF VAR VAR VAR VAR NUMBER IF VAR VAR IF VAR ASSIGN VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR VAR NUMBER VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def makePalindrome(self, arr, i, m):
start = 0
end = len(arr) - 1
count = 0
while start < end:
if arr[start] != arr[end]:
if start >= i and end <= i + m - 1:
return 1000000000.0
else:
count += 1
start += 1
end -= 1
return count
def specialPalindrome(self, s1, s2):
mini = 1000000000.0
m, n = len(s1), len(s2)
if m < n:
return -1
for i in range(0, m - n + 1):
count = 0
temp = list(s1)
for j in range(n):
if s1[i + j] != s2[j]:
count += 1
temp[i + j] = s2[j]
palin = self.makePalindrome(temp, i, n)
total = count + palin
mini = min(mini, total)
return -1 if mini == 1000000000.0 else mini | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR IF VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER RETURN NUMBER VAR NUMBER VAR NUMBER VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR NUMBER ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR RETURN NUMBER FOR VAR FUNC_CALL VAR NUMBER BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP VAR VAR VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR VAR ASSIGN VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR NUMBER NUMBER VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def solver(S, L, R):
steps = 0
for i in range(len(S) // 2):
if i >= L and len(S) - 1 - i <= R and S[i] != S[len(S) - 1 - i]:
return -1
if S[i] != S[len(S) - 1 - i]:
steps += 1
return steps
def specialPalindrome(ignore, s1, s2):
a, b = len(s1), len(s2)
if b > a:
return -1
cost = 10000
for i in range(a - b + 1):
localcost = 0
for j in range(b):
if s1[i + j] != s2[j]:
localcost += 1
s3 = s1[0:i] + s2 + s1[i + b :]
palincost = Solution.solver(s3, i, i + b - 1)
if palincost != -1:
localcost += palincost
cost = min(cost, localcost)
return -1 if cost == 10000 else cost | CLASS_DEF FUNC_DEF ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP FUNC_CALL VAR VAR NUMBER IF VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR VAR VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER VAR RETURN NUMBER IF VAR VAR VAR BIN_OP BIN_OP FUNC_CALL VAR VAR NUMBER VAR VAR NUMBER RETURN VAR FUNC_DEF ASSIGN VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR IF VAR VAR RETURN NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP VAR NUMBER VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR NUMBER VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR NUMBER NUMBER VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
if len(s2) > len(s1):
return -1
mini = -1
for i in range(len(s1) - len(s2) + 1):
st, end = i, i + len(s2) - 1
m, n = 0, len(s1) - 1
tmp = 0
stop = False
while n >= m:
c1, c2 = None, None
b1, b2 = False, False
if m == n:
if st <= m <= end:
c = s2[m - st]
if c != s1[m]:
tmp += 1
else:
if st <= m <= end:
c1 = s2[m - st]
b1 = True
if c1 != s1[m]:
tmp += 1
else:
c1 = s1[m]
if st <= n <= end:
c2 = s2[n - st]
b2 = True
if c2 != s1[n]:
tmp += 1
else:
c2 = s1[n]
if b1 and b2 and c1 != c2:
stop = True
break
if c1 != c2:
tmp += 1
m += 1
n -= 1
if not stop:
if mini == -1:
mini = tmp
else:
mini = min(mini, tmp)
return mini | CLASS_DEF FUNC_DEF IF FUNC_CALL VAR VAR FUNC_CALL VAR VAR RETURN NUMBER ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP FUNC_CALL VAR VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR FUNC_CALL VAR VAR NUMBER ASSIGN VAR VAR NUMBER BIN_OP FUNC_CALL VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR NUMBER WHILE VAR VAR ASSIGN VAR VAR NONE NONE ASSIGN VAR VAR NUMBER NUMBER IF VAR VAR IF VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR IF VAR VAR VAR VAR NUMBER IF VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR VAR ASSIGN VAR VAR BIN_OP VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR VAR NUMBER ASSIGN VAR VAR VAR IF VAR VAR VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR NUMBER VAR NUMBER VAR NUMBER IF VAR IF VAR NUMBER ASSIGN VAR VAR ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
ret = float("inf")
m = len(s1)
n = len(s2)
for i in range(m - n + 1):
s3 = list(s1[:i]) + list(s2) + list(s1[i + n :])
t = [1] * i + [0] * n + [1] * (m - i - n)
tmp = 0
for j in range(n):
if s1[i + j] != s2[j]:
tmp += 1
j = 0
k = m - 1
while j < k:
if s3[j] != s3[k]:
if t[j] == 1 or t[k] == 1:
tmp += 1
else:
tmp = float("inf")
break
j += 1
k -= 1
ret = min(ret, tmp)
return ret if ret != float("inf") else -1 | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR STRING ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR BIN_OP BIN_OP FUNC_CALL VAR VAR VAR FUNC_CALL VAR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP BIN_OP BIN_OP LIST NUMBER VAR BIN_OP LIST NUMBER VAR BIN_OP LIST NUMBER BIN_OP BIN_OP VAR VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR BIN_OP VAR VAR VAR VAR VAR NUMBER ASSIGN VAR NUMBER ASSIGN VAR BIN_OP VAR NUMBER WHILE VAR VAR IF VAR VAR VAR VAR IF VAR VAR NUMBER VAR VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR STRING VAR NUMBER VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR FUNC_CALL VAR STRING VAR NUMBER |
Given two strings s1 and s2, The task is to convert s1 into a palindrome such that s1 contain s2 as a substring in a minimum number of operation.
In a single operation, we can replace any word of s1 with any character.
Note: If it is not possible to convert s1 such that it is a palindrome as well as contains substring of s2, then return -1.
Example 1:
Input:
s1="abaa" s2="bb"
Output: 1
Explanation:
we can replace s1[2]='a' with 'b'.
So the new s1 will be like "abba",
having s2 as a substring.
Example 2:
Input:
s1="abbd" s2="mr"
Output: 4
Explanation:
1st: s1="mrbd" --> 2 operations (this is the
minimum operation to make s2 a substring of s1)
2nd: s1="mrrm" --> 2 operations
(this is the minimum operation to make s1 palindrome)
Your Task:
You don't need to read input or print anything. Complete the function specialPalindrome() which takes the two strings s1 and s2 as input parameters. Return the minimum number of operations needs to convert s1 such that it is a palindrome and having s2 as a substring in s1.
Expected Time Complexity: O(N*M) [N: size of s1 and M: size of s2]
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ |s2| ≤ |s1| ≤ 1000 | class Solution:
def specialPalindrome(self, s1, s2):
s1 = list(s1)
s2 = list(s2)
n = len(s1)
m = len(s2)
ans = n + 1
for i in range(n - m + 1):
s = s1.copy()
for j in range(i, i + m):
s[j] = s2[j - i]
pos = True
for j in range(n):
if s[j] != s[n - j - 1]:
if j >= i and j < i + m and n - j - 1 >= i and n - j - 1 < i + m:
pos = False
break
if j >= i and j < i + m:
s[n - j - 1] = s[j]
else:
s[j] = s[n - j - 1]
if not pos:
continue
cnt = 0
for i in range(n):
if s[i] != s1[i]:
cnt += 1
ans = min(ans, cnt)
return -1 if ans == n + 1 else ans | CLASS_DEF FUNC_DEF ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR FUNC_CALL VAR VAR ASSIGN VAR BIN_OP VAR NUMBER FOR VAR FUNC_CALL VAR BIN_OP BIN_OP VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR FOR VAR FUNC_CALL VAR VAR BIN_OP VAR VAR ASSIGN VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR VAR VAR BIN_OP VAR VAR BIN_OP BIN_OP VAR VAR NUMBER VAR BIN_OP BIN_OP VAR VAR NUMBER BIN_OP VAR VAR ASSIGN VAR NUMBER IF VAR VAR VAR BIN_OP VAR VAR ASSIGN VAR BIN_OP BIN_OP VAR VAR NUMBER VAR VAR ASSIGN VAR VAR VAR BIN_OP BIN_OP VAR VAR NUMBER IF VAR ASSIGN VAR NUMBER FOR VAR FUNC_CALL VAR VAR IF VAR VAR VAR VAR VAR NUMBER ASSIGN VAR FUNC_CALL VAR VAR VAR RETURN VAR BIN_OP VAR NUMBER NUMBER VAR |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.