question
stringlengths
29
14k
solutions
listlengths
1
6.39k
starter_code
stringlengths
0
1.47k
input_output
stringlengths
29
74M
difficulty
stringclasses
6 values
raw_tags
stringlengths
2
281
name
stringlengths
3
105
source
stringclasses
10 values
tags
stringlengths
2
183
skill_types
stringclasses
127 values
url
stringlengths
36
138
time_limit
stringclasses
143 values
date
stringlengths
10
10
picture_num
stringclasses
8 values
memory_limit
stringclasses
28 values
Expected Time Complexity
stringclasses
710 values
task_id
int64
1
25.4k
solution_id
int64
0
0
solution
stringlengths
6
413k
text
stringlengths
123
413k
Implement a Stack using two queues q1 and q2. Example 1: Input: push(2) push(3) pop() push(4) pop() Output: 3 4 Explanation: push(2) the stack will be {2} push(3) the stack will be {2 3} pop() poped element will be 3 the stack will be {2} push(4) the stack will be {2 4} pop() poped element will be 4 Exam...
[ "def push(x):\n\tglobal queue_1\n\tglobal queue_2\n\tqueue_1.append(x)\n\twhile queue_2:\n\t\tval = queue_2.pop(0)\n\t\tqueue_1.append(val)\n\t(queue_1, queue_2) = (queue_2, queue_1)\n\ndef pop():\n\tglobal queue_1\n\tglobal queue_2\n\tif not queue_2:\n\t\treturn -1\n\treturn queue_2.pop(0)\n", "def push(x):\n\tg...
#User function Template for python3 ''' :param x: value to be inserted :return: None queue_1 = [] # first queue queue_2 = [] # second queue ''' #Function to push an element into stack using two queues. def push(x): # global declaration global queue_1 global queue_2 # co...
{"fn_name": "push", "inputs": ["push(2)\npush(3)\npop()\npush(4)\npop()", "push(2)\npop()\npop()\npush(3)"], "outputs": ["3 4", "2 -1"]}
EASY
['Stack', 'Data Structures', 'Queue', 'Design-Pattern']
null
geeksforgeeks
['Data structures']
['Data structures']
https://practice.geeksforgeeks.org/problems/stack-using-two-queues/1
null
null
0
null
O(1) for push() and O(N) for pop() (or vice-versa).
25,328
0
def push(x): global queue_1 global queue_2 queue_1.append(x) while queue_2: val = queue_2.pop(0) queue_1.append(val) (queue_1, queue_2) = (queue_2, queue_1) def pop(): global queue_1 global queue_2 if not queue_2: return -1 return queue_2.pop(0)
# Question Implement a Stack using two queues q1 and q2. Example 1: Input: push(2) push(3) pop() push(4) pop() Output: 3 4 Explanation: push(2) the stack will be {2} push(3) the stack will be {2 3} pop() poped element will be 3 the stack will be {2} push(4) the stack will be {2 4} pop() poped element will...
An employee's wallet can contain no more than M notes or coins. A boss pays his salary by the minimum notes possible. However the employee may have to leave out some money. Find how much money he has to lose if his original salary is N. Note: The values of notes or coins available are 1000, 500, 100, 50, 20, 10, 5, 2 a...
[ "class Solution:\n\n\tdef getLoss(self, n, m):\n\t\tnotes = [1000, 500, 100, 50, 20, 10, 5, 2, 1]\n\t\tcount = 0\n\t\ti = 0\n\t\twhile count < m and n > 0:\n\t\t\tif n >= notes[i]:\n\t\t\t\tn = n - notes[i]\n\t\t\t\tcount += 1\n\t\t\telse:\n\t\t\t\ti += 1\n\t\treturn n\n", "class Solution:\n\n\tdef getLoss(self, ...
#User function Template for python3 class Solution: def getLoss(self, N, M): # code here
{"inputs": ["N = 1712, M = 4", "N = 1023, M = 2"], "outputs": ["12", "3"]}
EASY
['Algorithms', 'Mathematical']
null
geeksforgeeks
['Mathematics']
[]
https://practice.geeksforgeeks.org/problems/minimum-notes-required2535/1
null
null
0
null
O(1)
25,329
0
class Solution: def getLoss(self, n, m): notes = [1000, 500, 100, 50, 20, 10, 5, 2, 1] count = 0 i = 0 while count < m and n > 0: if n >= notes[i]: n = n - notes[i] count += 1 else: i += 1 return n
# Question An employee's wallet can contain no more than M notes or coins. A boss pays his salary by the minimum notes possible. However the employee may have to leave out some money. Find how much money he has to lose if his original salary is N. Note: The values of notes or coins available are 1000, 500, 100, 50, 20...
Ricky has N different balls and John has R different bags. Their teacher Ms.Samara wants them to distribute these N balls into R bags such that each bag gets at least one ball. Can you find the number of ways of doing so ? Input: The one and only line of input contains two numbers separated by a single space, which a...
[ "'''\n# Read input from stdin and provide input before running code\n\nname = raw_input('What is your name?\\n')\nprint 'Hi, %s.' % name\n'''\n#print 'Hello World!'\nfrom math import factorial\nn,k=list(map(int,input().split()))\nif n>=k:\n\tf=factorial(n-1)/(factorial(n-k)*factorial(k-1))\n\tprint(f%10000007)\nels...
{"inputs": ["43 42", "8 2", "11 23", "42 32", "22 19"], "outputs": ["-1", "42", "1330", "7", "1098624"]}
UNKNOWN_DIFFICULTY
[]
can-you-distribute
hackerearth
[]
[]
null
null
null
null
null
null
25,331
0
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' from math import factorial n,k=list(map(int,input().split())) if n>=k: f=factorial(n-1)/(factorial(n-k)*factorial(k-1)) print(f%10000007) else: print("-1")
# Question Ricky has N different balls and John has R different bags. Their teacher Ms.Samara wants them to distribute these N balls into R bags such that each bag gets at least one ball. Can you find the number of ways of doing so ? Input: The one and only line of input contains two numbers separated by a single sp...
Sid is a superior salesperson. So he gets a task from his boss. The task is that he will be given some number of products say k (All the products are same) and he has to travel N cities [1...N] to sell them. The main objective of the task is that he has to try to sell the product at higher price than previous city. For...
[ "primes = [2, 3]\n\nclass Solution:\n\n\tdef primeMoney(self, arr, n):\n\t\tmaxi = max(arr)\n\t\ti = primes[-1] + 2\n\t\twhile maxi >= i:\n\t\t\tflag = True\n\t\t\tfor item in primes:\n\t\t\t\tif i % item == 0:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\t\t\tif flag:\n\t\t\t\tprimes.append(i)\n\t\t\ti += 2\n\t\tset...
#User function Template for python3 class Solution: def primeMoney(self, arr, n): # return (0,0)
{"inputs": ["N = 9\nA[] = {4, 2, 3, 5, 1, 6, 7, 8, 9}", "N = 10\nA[] = {2, 3, 5, 7, 4, 1, 6, 5, 4, 8}", "N = 5\nA[] = {2, 2, 2, 2, 2}"], "outputs": ["5 7", "4 17", "1 2"]}
EASY
['Data Structures', 'Arrays', 'Algorithms', 'Mathematical']
null
geeksforgeeks
['Data structures', 'Mathematics']
['Data structures']
https://practice.geeksforgeeks.org/problems/sid-and-his-prime-money5736/1
null
null
0
null
O(N. sqrt(N))
25,330
0
primes = [2, 3] class Solution: def primeMoney(self, arr, n): maxi = max(arr) i = primes[-1] + 2 while maxi >= i: flag = True for item in primes: if i % item == 0: flag = False break if flag: primes.append(i) i += 2 setti = set(primes) count = 0 summa = 0 last = 0 temp_c...
# Question Sid is a superior salesperson. So he gets a task from his boss. The task is that he will be given some number of products say k (All the products are same) and he has to travel N cities [1...N] to sell them. The main objective of the task is that he has to try to sell the product at higher price than previo...
Chef usually likes to play cricket, but now, he is bored of playing it too much, so he is trying new games with strings. Chef's friend Dustin gave him binary strings $S$ and $R$, each with length $N$, and told him to make them identical. However, unlike Dustin, Chef does not have any superpower and Dustin lets Chef per...
[ "for i in range(int(input())):\n\ta = int(input())\n\tb = input()\n\tc = input()\n\td = b.count('0')\n\te = c.count('0')\n\tif d == e:\n\t\tprint('YES')\n\telse:\n\t\tprint('NO')\n", "for _ in range(int(input())):\n\tn = int(input())\n\ta = input()\n\tb = input()\n\tif a.count('1') == b.count('1'):\n\t\tprint('YE...
{"inputs": [["2", "5", "11000", "01001", "3", "110", "001"]], "outputs": [["YES", "NO"]]}
EASY
['Data Structures', 'Arrays', 'Frequency Arrays']
null
codechef
['Data structures']
['Data structures']
https://www.codechef.com/problems/PLAYSTR
1 seconds
2019-07-12
0
50000 bytes
null
25,327
0
for i in range(int(input())): a = int(input()) b = input() c = input() d = b.count('0') e = c.count('0') if d == e: print('YES') else: print('NO')
# Question Chef usually likes to play cricket, but now, he is bored of playing it too much, so he is trying new games with strings. Chef's friend Dustin gave him binary strings $S$ and $R$, each with length $N$, and told him to make them identical. However, unlike Dustin, Chef does not have any superpower and Dustin l...
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solu...
[ "class Solution:\n\n\tdef maxSubArray(self, nums):\n\t\tmax_sum = csum = nums[0]\n\t\tfor num in nums[1:]:\n\t\t\tif num >= csum + num:\n\t\t\t\tcsum = num\n\t\t\telse:\n\t\t\t\tcsum += num\n\t\t\tif csum > max_sum:\n\t\t\t\tmax_sum = csum\n\t\treturn max_sum\n", "class Solution:\n\n\tdef maxSubArray(self, nums):...
class Solution: def maxSubArray(self, nums: List[int]) -> int:
{"fn_name": "maxSubArray", "inputs": [[[-2, 1, -3, 4, -1, 2, 1, -5, 4]]], "outputs": [6]}
EASY
['Array', 'Dynamic Programming', 'Divide and Conquer']
null
leetcode
['Dynamic programming', 'Data structures', 'Divide and conquer']
['Dynamic programming', 'Data structures']
https://leetcode.com/problems/maximum-subarray/
null
null
null
null
null
25,332
0
class Solution: def maxSubArray(self, nums): max_sum = csum = nums[0] for num in nums[1:]: if num >= csum + num: csum = num else: csum += num if csum > max_sum: max_sum = csum return max_sum
# Question Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding ...
In Python, a string of text can be aligned left, right and center. .ljust(width) This method returns a left aligned string of length width. >>> width = 20 >>> print 'HackerRank'.ljust(width,'-') HackerRank---------- .center(width) This method returns a centered string of length width. >>> width = 20 >>> print '...
[ "thickness = int(input())\nc = 'H'\nfor i in range(thickness):\n\tprint((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1))\nfor i in range(thickness + 1):\n\tprint((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6))\nfor i in range((thickness + 2) // 2):\n\tprint((c * thickn...
{"inputs": ["5\n"], "outputs": [" H \n HHH \n HHHHH \n HHHHHHH \nHHHHHHHHH\n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH HHHHH \n HHHHH ...
EASY
['Python - Strings']
null
hackerrank
['String algorithms']
[]
https://www.hackerrank.com/challenges/text-alignment/problem
null
null
0
null
null
25,336
0
thickness = int(input()) c = 'H' for i in range(thickness): print((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1)) for i in range(thickness + 1): print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) for i in range((thickness + 2) // 2): print((c * thickness * 5).center...
# Question In Python, a string of text can be aligned left, right and center. .ljust(width) This method returns a left aligned string of length width. >>> width = 20 >>> print 'HackerRank'.ljust(width,'-') HackerRank---------- .center(width) This method returns a centered string of length width. >>> width = 20...
You are given N integers \{A_{1}, A_{2}, \ldots, A_{N}\}. Determine whether they can be reordered such that each pair of consecutive differences differ by a factor of 2. Formally, determine whether there exists a rearrangement of the given integers into an array [B_{1}, B_{2}, \ldots, B_{N}] such that, for each 2 ≤ i ...
[ "for _ in range(int(input())):\n\tn = int(input())\n\ta = sorted(list(map(int, input().split())))\n\tl = [a[i + 1] - a[i] for i in range(n - 1)]\n\tc = 0\n\tfor i in range(len(l) - 1):\n\t\tif l[i] == 2 * l[i + 1] or l[i] // 2 == l[i + 1] or 2 * l[i] == l[i + 1]:\n\t\t\tc += 1\n\t\telse:\n\t\t\tbreak\n\tif len(l) -...
{"inputs": ["4\n3\n5 2 4\n5\n2 1 16 8 4\n5\n97 98 100 96 88\n6\n16 19 18 21 24 22"], "outputs": ["Yes\nYes\nNo\nYes\n"]}
EASY
['ad-hoc', 'trygub_adm', 'sorting', 'cook141']
null
codechef
['Sorting', 'Ad-hoc']
['Sorting']
https://www.codechef.com/problems/DOUBLEDDIST
1 seconds
2022-04-28
0
50000 bytes
null
25,334
0
for _ in range(int(input())): n = int(input()) a = sorted(list(map(int, input().split()))) l = [a[i + 1] - a[i] for i in range(n - 1)] c = 0 for i in range(len(l) - 1): if l[i] == 2 * l[i + 1] or l[i] // 2 == l[i + 1] or 2 * l[i] == l[i + 1]: c += 1 else: break if len(l) - 1 == c: print('Yes') else: ...
# Question You are given N integers \{A_{1}, A_{2}, \ldots, A_{N}\}. Determine whether they can be reordered such that each pair of consecutive differences differ by a factor of 2. Formally, determine whether there exists a rearrangement of the given integers into an array [B_{1}, B_{2}, \ldots, B_{N}] such that, for...
Example Input 4 4 1 2 3 1 3 3 2 3 3 2 4 3 Output 1 3
[ "(N, M) = map(int, input().split())\nE0 = []\nfor i in range(M):\n\t(S, D, C) = map(int, input().split())\n\tE0.append((C, S - 1, D - 1))\nE0.sort()\n(*parent,) = range(N)\n\ndef root(x):\n\tif x == parent[x]:\n\t\treturn x\n\ty = parent[x] = root(parent[x])\n\treturn y\n\ndef unite(x, y):\n\tpx = root(x)\n\tpy = r...
{"inputs": ["4 4\n1 2 3\n1 3 3\n2 3 3\n2 4 6", "4 4\n1 2 4\n1 3 3\n2 3 3\n2 4 6", "4 4\n1 3 4\n1 3 0\n2 3 3\n2 4 6", "4 4\n1 3 4\n1 3 0\n2 3 5\n2 4 6", "4 4\n1 2 3\n1 3 3\n2 3 3\n2 4 9", "4 4\n1 4 3\n1 3 0\n2 3 5\n2 4 6", "4 4\n1 2 2\n1 3 3\n2 3 3\n2 4 3", "4 4\n1 2 4\n1 3 3\n2 3 3\n1 4 11", "4 4\n1 2 1\n1 3 3\n2 3 3\n...
UNKNOWN_DIFFICULTY
[]
null
aizu
[]
[]
null
3.0 seconds
null
null
268.435456 megabytes
null
25,337
0
(N, M) = map(int, input().split()) E0 = [] for i in range(M): (S, D, C) = map(int, input().split()) E0.append((C, S - 1, D - 1)) E0.sort() (*parent,) = range(N) def root(x): if x == parent[x]: return x y = parent[x] = root(parent[x]) return y def unite(x, y): px = root(x) py = root(y) if px < py: parent[p...
# Question Example Input 4 4 1 2 3 1 3 3 2 3 3 2 4 3 Output 1 3 # Solution ```python (N, M) = map(int, input().split()) E0 = [] for i in range(M): (S, D, C) = map(int, input().split()) E0.append((C, S - 1, D - 1)) E0.sort() (*parent,) = range(N) def root(x): if x == parent[x]: return x y = parent[x] = ro...
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One ...
[ "import sys\ninput = sys.stdin.readline\nimport heapq\n(n, m, k) = map(int, input().split())\nadj = [[] for _ in range(n + 5)]\nfor _ in range(m):\n\t(u, v, w) = map(int, input().split())\n\tadj[u].append((v, w))\n\tadj[v].append((u, w))\ntrain = [-1 for _ in range(n + 5)]\nans = 0\ndist = [int(1000000000000000.0) ...
{"inputs": ["5 5 2\n1 2 100\n2 3 100\n3 4 100\n4 5 20\n2 5 5\n5 50\n4 1\n", "2 1 5\n1 2 4\n2 3\n2 5\n2 4\n2 4\n2 5\n", "3 3 6\n1 2 499999999\n2 3 500000000\n1 3 999999999\n2 499999999\n2 500000000\n2 499999999\n3 999999999\n3 1000000000\n3 1000000000\n", "2 1 1\n1 2 1\n2 1000000000\n", "5 4 3\n1 2 999999999\n2 3 100000...
HARD
['shortest paths', 'greedy', 'graphs']
null
codeforces
['Greedy algorithms', 'Graph algorithms', 'Shortest paths']
['Greedy algorithms']
https://codeforces.com/problemset/problem/450/D
2.0 seconds
null
null
256.0 megabytes
null
25,338
0
import sys input = sys.stdin.readline import heapq (n, m, k) = map(int, input().split()) adj = [[] for _ in range(n + 5)] for _ in range(m): (u, v, w) = map(int, input().split()) adj[u].append((v, w)) adj[v].append((u, w)) train = [-1 for _ in range(n + 5)] ans = 0 dist = [int(1000000000000000.0) for _ in range(n + ...
# Question Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the c...
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any ...
[ "from itertools import combinations_with_replacement\nfrom collections import deque\n(n, m) = map(int, input().split())\nG = [[] for i in range(n)]\nfor i in range(m):\n\t(x, y) = map(int, input().split())\n\tx -= 1\n\ty -= 1\n\tG[x].append(y)\n\tG[y].append(x)\n\ndef BFS(s):\n\tdist = [-1 for i in range(n)]\n\tdis...
{"inputs": ["2 1\n1 2\n1 1 0\n1 2 0\n", "1 0\n1 1 0\n1 1 0\n", "2 1\n1 2\n1 1 0\n1 2 1\n", "6 5\n1 2\n2 3\n3 4\n3 5\n2 6\n1 4 3\n5 6 3\n", "9 9\n1 2\n2 3\n2 4\n4 5\n5 7\n5 6\n3 8\n8 9\n9 6\n1 7 4\n3 6 3\n", "10 11\n1 3\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\n4 9\n4 10\n7 9\n8 10\n1 5 3\n6 2 3\n", "6 5\n1 3\n2 3\n3 4\n4 5\n4 6\n...
HARD
['shortest paths', 'graphs', 'constructive algorithms']
null
codeforces
['Graph algorithms', 'Shortest paths', 'Constructive algorithms']
[]
https://codeforces.com/problemset/problem/544/D
2.0 seconds
null
null
256.0 megabytes
null
25,339
0
from itertools import combinations_with_replacement from collections import deque (n, m) = map(int, input().split()) G = [[] for i in range(n)] for i in range(m): (x, y) = map(int, input().split()) x -= 1 y -= 1 G[x].append(y) G[y].append(x) def BFS(s): dist = [-1 for i in range(n)] dist[s] = 0 Q = deque() Q....
# Question In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such th...
Alexa has two stacks of non-negative integers, stack $a[n]$ and stack $b[m]$ where index $0$ denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack $\class{ML__boldsymbol}{\boldsymbol{a}}$ or stack $\boldsymbol{b}$. Nick ke...
[ "import sys\ng = int(input().strip())\nfor a0 in range(g):\n\t(n, m, x) = input().strip().split(' ')\n\t(n, m, x) = [int(n), int(m), int(x)]\n\ta = list(map(int, input().strip().split(' ')))\n\tb = list(map(int, input().strip().split(' ')))\n\ti = 0\n\twhile i < len(a) and x >= a[i]:\n\t\tx -= a[i]\n\t\ti += 1\n\ta...
{"inputs": ["1\n5 4 10\n4 2 4 6 1\n2 1 8 5\n"], "outputs": ["4\n"]}
MEDIUM
['Data Structures - Stacks']
null
hackerrank
['Data structures']
['Data structures']
https://www.hackerrank.com/challenges/game-of-two-stacks/problem
null
null
2
null
null
25,333
0
import sys g = int(input().strip()) for a0 in range(g): (n, m, x) = input().strip().split(' ') (n, m, x) = [int(n), int(m), int(x)] a = list(map(int, input().strip().split(' '))) b = list(map(int, input().strip().split(' '))) i = 0 while i < len(a) and x >= a[i]: x -= a[i] i += 1 ans = i j = 0 for p in b: ...
# Question Alexa has two stacks of non-negative integers, stack $a[n]$ and stack $b[m]$ where index $0$ denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack $\class{ML__boldsymbol}{\boldsymbol{a}}$ or stack $\boldsymbol{...
A tennis tournament is about to take place with $N$ players participating in it. Every player plays with every other player exactly once and there are no ties. That is, every match has a winner and a loser. With Naman's birthday approaching, he wants to make sure that each player wins the same number of matches so tha...
[ "from math import comb\na = int(input())\nfor i in range(a):\n\tN = int(input())\n\tmatche = comb(N, 2)\n\twin = matche / N\n\tans = []\n\tif win != int(win):\n\t\tprint('NO')\n\t\tcontinue\n\tprint('YES')\n\tfor k in range(N):\n\t\tlist = []\n\t\tfor j in range(N):\n\t\t\tlist.append(0)\n\t\tans.append(list)\n\t\t...
{"inputs": [["2", "3", "2"]], "outputs": [["YES", "010", "001", "100", "NO"]]}
MEDIUM
['Algorithms', 'ad-hoc', 'Observation', 'Constructive']
null
codechef
['Constructive algorithms', 'Ad-hoc']
[]
https://www.codechef.com/problems/EXUNB
1 seconds
2019-09-25
0
50000 bytes
null
25,340
0
from math import comb a = int(input()) for i in range(a): N = int(input()) matche = comb(N, 2) win = matche / N ans = [] if win != int(win): print('NO') continue print('YES') for k in range(N): list = [] for j in range(N): list.append(0) ans.append(list) list = [] for k in range(N): temp = win ...
# Question A tennis tournament is about to take place with $N$ players participating in it. Every player plays with every other player exactly once and there are no ties. That is, every match has a winner and a loser. With Naman's birthday approaching, he wants to make sure that each player wins the same number of ma...
Given a set of $N$ axis-aligned rectangular seals, find the number of overlapped seals on the region which has the maximum number of overlapped seals. Constraints * $ 1 \leq N \leq 100000 $ * $ 0 \leq x1_i < x2_i \leq 1000 $ * $ 0 \leq y1_i < y2_i \leq 1000 $ * $ x1_i, y1_i, x2_i, y2_i$ are given in integers Input ...
[ "from itertools import accumulate\nimport sys\nn = int(input())\nys = [0] * 1001\nrects = [None] * 2 * n\ni = 0\nfor line in sys.stdin:\n\t(x1, y1, x2, y2) = [int(j) for j in line.split()]\n\trects[i] = (x2, -1, y1, y2)\n\trects[i + n] = (x1, 1, y1, y2)\n\ti += 1\nrects.sort(key=lambda x: x[0])\nmax_overlap = 0\nfo...
{"inputs": ["2\n0 0 2 2\n2 0 4 4", "3\n0 0 1 2\n0 0 2 2\n0 0 2 2", "2\n0 0 3 2\n2 1 4 2", "2\n0 0 0 1\n2 2 4 2", "2\n0 0 3 1\n2 1 4 3", "2\n0 0 3 1\n2 1 4 2", "2\n0 0 3 1\n2 1 4 4", "2\n0 0 2 2\n2 0 2 2", "3\n0 0 2 4\n0 0 2 2\n0 0 2 2", "3\n0 0 1 2\n0 0 2 3\n0 0 2 2", "2\n0 0 3 1\n2 1 2 3", "2\n0 0 3 1\n2 2 4 2", "2\n0...
UNKNOWN_DIFFICULTY
[]
null
aizu
[]
[]
null
1.0 seconds
null
null
134.217728 megabytes
null
25,342
0
from itertools import accumulate import sys n = int(input()) ys = [0] * 1001 rects = [None] * 2 * n i = 0 for line in sys.stdin: (x1, y1, x2, y2) = [int(j) for j in line.split()] rects[i] = (x2, -1, y1, y2) rects[i + n] = (x1, 1, y1, y2) i += 1 rects.sort(key=lambda x: x[0]) max_overlap = 0 for (x, t, y1, y2) in re...
# Question Given a set of $N$ axis-aligned rectangular seals, find the number of overlapped seals on the region which has the maximum number of overlapped seals. Constraints * $ 1 \leq N \leq 100000 $ * $ 0 \leq x1_i < x2_i \leq 1000 $ * $ 0 \leq y1_i < y2_i \leq 1000 $ * $ x1_i, y1_i, x2_i, y2_i$ are given in integ...
You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $x$. You need to select the maximum number of elements in the array, such that for every subsegment $a_l, a_{l + 1}, \ldots, a_r$ containing strictly more than one element $(l < r)$, either: At least one element on this subsegment is not select...
[ "for _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tx = int(input())\n\ta = [c - x for c in a]\n\tbegin = True\n\tunchosen = 0\n\tsum = 0\n\tfor i in range(n):\n\t\tif begin:\n\t\t\tsum = a[i]\n\t\t\tbegin = False\n\t\telse:\n\t\t\tsum += a[i]\n\t\t\tif sum < 0:\n\t\t\t\tbeg...
{"inputs": ["4\n5\n1 2 3 4 5\n2\n10\n2 4 2 4 2 4 2 4 2 4\n3\n3\n-10 -5 -10\n-8\n3\n9 9 -3\n5\n", "1\n10\n5 -9 -1 6 -6 5 -6 -8 5 3\n0\n", "10\n1\n62169\n62169\n1\n49900\n49900\n1\n-45220\n-45220\n1\n45734\n45734\n1\n-77581\n-77581\n1\n-48287\n-48287\n1\n53304\n53304\n1\n13558\n13558\n1\n18202\n18202\n1\n33613\n33613\n",...
HARD
['greedy', 'math', 'dp']
null
codeforces
['Dynamic programming', 'Mathematics', 'Greedy algorithms']
['Dynamic programming', 'Greedy algorithms']
https://codeforces.com/problemset/problem/1616/D
1.5 seconds
2021-12-29
0
256 megabytes
null
25,343
0
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) x = int(input()) a = [c - x for c in a] begin = True unchosen = 0 sum = 0 for i in range(n): if begin: sum = a[i] begin = False else: sum += a[i] if sum < 0: begin = True unchosen += 1 else: sum = m...
# Question You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $x$. You need to select the maximum number of elements in the array, such that for every subsegment $a_l, a_{l + 1}, \ldots, a_r$ containing strictly more than one element $(l < r)$, either: At least one element on this subsegment i...
It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing the husband's...
[ "def match(usefulness, months):\n\treturn 'Match!' if sum(usefulness) >= 0.85 ** months * 100 else 'No match!'\n", "def current(usefulness):\n\treturn sum(usefulness)\n\ndef needed(months):\n\tif months == 0:\n\t\treturn 100\n\telse:\n\t\treturn 0.85 * needed(months - 1)\n\ndef match(usefulness, months):\n\tif cu...
def match(usefulness, months):
{"fn_name": "match", "inputs": [[[15, 24, 12], 4], [[26, 23, 19], 3], [[11, 25, 36], 1], [[22, 9, 24], 5], [[8, 11, 4], 10], [[17, 31, 21], 2], [[34, 25, 36], 1], [[35, 35, 29], 0], [[35, 35, 30], 0], [[35, 35, 31], 0]], "outputs": [["No match!"], ["Match!"], ["No match!"], ["Match!"], ["Match!"], ["No match!"], ["Matc...
EASY
['Mathematics', 'Algorithms', 'Fundamentals']
null
codewars
['Fundamentals', 'Mathematics']
[]
https://www.codewars.com/kata/5750699bcac40b3ed80001ca
null
null
null
null
null
25,345
0
def match(usefulness, months): return 'Match!' if sum(usefulness) >= 0.85 ** months * 100 else 'No match!'
# Question It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing t...
Problem Statement Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and always tries to save as much paper as possible. She decided to play a ghost leg with other participants to decide the team for the Aizu training camp. How to make Amidakuji for this training camp is as foll...
[ "from itertools import permutations\n(N, M) = map(int, input().split())\nk = [int(input()) - 1 for i in range(M)]\ng = [i for i in range(N)]\nfor i in range(N):\n\tfor j in k:\n\t\tif g[i] == j:\n\t\t\tg[i] = j + 1\n\t\telif g[i] == j + 1:\n\t\t\tg[i] = j\ns = 10\nfor K in permutations(k):\n\tG = [i for i in range(...
{"inputs": ["6 4\n4\n3\n1\n2", "4 3\n2\n2\n4", "13 1\n7\n4\n3", "6 4\n1\n2\n1\n2", "4 3\n2\n2\n3", "5 3\n2\n2\n3", "4 3\n2\n3\n4", "4 3\n3\n3\n4", "6 4\n4\n1\n1\n2", "5 3\n4\n2\n3", "9 3\n4\n2\n3", "9 3\n4\n2\n4", "4 3\n1\n2\n2", "10 4\n4\n3\n1\n2", "7 3\n2\n2\n4", "9 3\n2\n2\n3", "6 3\n2\n3\n4", "4 3\n3\n4\n4", "12 4\...
UNKNOWN_DIFFICULTY
[]
null
aizu
[]
[]
null
1.0 seconds
null
null
134.217728 megabytes
null
25,351
0
from itertools import permutations (N, M) = map(int, input().split()) k = [int(input()) - 1 for i in range(M)] g = [i for i in range(N)] for i in range(N): for j in k: if g[i] == j: g[i] = j + 1 elif g[i] == j + 1: g[i] = j s = 10 for K in permutations(k): G = [i for i in range(N)] for i in range(N): for...
# Question Problem Statement Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and always tries to save as much paper as possible. She decided to play a ghost leg with other participants to decide the team for the Aizu training camp. How to make Amidakuji for this training cam...
A number is called faithful if you can write it as the sum of distinct powers of 7. e.g., 2457 = 7 + 7^{2} + 7^{4 . }If we order all the faithful numbers, we get the sequence 1 = 7^{0}, 7 = 7^{1}, 8 = 7^{0} + 7^{1}, 49 = 7^{2}, 50 = 7^{0} + 7^{2} . . . and so on. Given some value of N, you have to find the N'th faith...
[ "class Solution:\n\n\tdef nthFaithfulNum(self, N):\n\t\tans = 0\n\t\tpower = 0\n\t\twhile N:\n\t\t\tif N & 1:\n\t\t\t\tans = ans + pow(7, power)\n\t\t\tpower = power + 1\n\t\t\tN = N // 2\n\t\treturn ans\n", "class Solution:\n\n\tdef nthFaithfulNum(self, N):\n\t\td = 1\n\t\ti = 1\n\t\tres = 0\n\t\twhile i <= N:\n...
#User function Template for python3 class Solution: def nthFaithfulNum(self, N): # code here
{"inputs": ["N = 3", "N = 7"], "outputs": ["8", "57"]}
EASY
['Algorithms', 'Mathematical']
null
geeksforgeeks
['Mathematics']
[]
https://practice.geeksforgeeks.org/problems/faithful-numbers0014/1
null
null
0
null
O(log(N))
25,347
0
class Solution: def nthFaithfulNum(self, N): ans = 0 power = 0 while N: if N & 1: ans = ans + pow(7, power) power = power + 1 N = N // 2 return ans
# Question A number is called faithful if you can write it as the sum of distinct powers of 7. e.g., 2457 = 7 + 7^{2} + 7^{4 . }If we order all the faithful numbers, we get the sequence 1 = 7^{0}, 7 = 7^{1}, 8 = 7^{0} + 7^{1}, 49 = 7^{2}, 50 = 7^{0} + 7^{2} . . . and so on. Given some value of N, you have to find th...
Given an array Arr of size N, print second largest distinct element from an array. Example 1: Input: N = 6 Arr[] = {12, 35, 1, 10, 34, 1} Output: 34 Explanation: The largest element of the array is 35 and the second largest element is 34. Example 2: Input: N = 3 Arr[] = {10, 5, 10} Output: 5 Explanation: The largest...
[ "class Solution:\n\n\tdef print2largest(self, arr, n):\n\t\tif n < 2:\n\t\t\treturn -1\n\t\t(largest, second_largest) = (float('-inf'), float('-inf'))\n\t\tfor i in range(n):\n\t\t\tif arr[i] > largest:\n\t\t\t\tsecond_largest = largest\n\t\t\t\tlargest = arr[i]\n\t\t\telif arr[i] > second_largest and arr[i] != lar...
#User function Template for python3 class Solution: def print2largest(self,arr, n): # code here
{"inputs": ["N = 6\nArr[] = {12, 35, 1, 10, 34, 1}", "N = 3\nArr[] = {10, 5, 10}"], "outputs": ["34", "5"]}
EASY
['Data Structures', 'Arrays', 'Searching', 'Algorithms']
null
geeksforgeeks
['Data structures', 'Complete search']
['Data structures', 'Complete search']
https://practice.geeksforgeeks.org/problems/second-largest3735/1
null
null
0
null
O(N)
25,350
0
class Solution: def print2largest(self, arr, n): if n < 2: return -1 (largest, second_largest) = (float('-inf'), float('-inf')) for i in range(n): if arr[i] > largest: second_largest = largest largest = arr[i] elif arr[i] > second_largest and arr[i] != largest: second_largest = arr[i] if ...
# Question Given an array Arr of size N, print second largest distinct element from an array. Example 1: Input: N = 6 Arr[] = {12, 35, 1, 10, 34, 1} Output: 34 Explanation: The largest element of the array is 35 and the second largest element is 34. Example 2: Input: N = 3 Arr[] = {10, 5, 10} Output: 5 Explanation:...
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. Write a program to count the number of black tiles which he can r...
[ "from collections import deque\ny = [-1, 0, 1, 0]\nx = [0, -1, 0, 1]\n\ndef main():\n\t(h, w) = (0, 0)\n\tc = []\n\n\tdef check(i, j):\n\t\treturn 0 <= i and i < h and (0 <= j) and (j < w)\n\n\tdef bfs(a, b):\n\t\tres = 0\n\t\td = deque()\n\t\td.append([a, b])\n\t\tf = [[False] * w for _ in range(h)]\n\t\twhile len...
{"inputs": ["6 9\n....#.\n.....#\n......\n......\n......\n......\n......\n@...#\n.#..#.\n11 9\n.#.........\n.#.#######.\n.#.#.....#.\n.#.#.###.#.\n.#.#..@#.#.\n.#.#####.#.\n.#.......#.\n.#########.\n...........\n11 6\n..#..#..#..\n..#..#..#..\n..#..#..###\n..#..#..#@.\n..#..#..#..\n..#..#..#..\n7 7\n#.#....\n..#.#..\n....
UNKNOWN_DIFFICULTY
[]
null
aizu
[]
[]
null
1.0 seconds
null
null
134.217728 megabytes
null
25,349
0
from collections import deque y = [-1, 0, 1, 0] x = [0, -1, 0, 1] def main(): (h, w) = (0, 0) c = [] def check(i, j): return 0 <= i and i < h and (0 <= j) and (j < w) def bfs(a, b): res = 0 d = deque() d.append([a, b]) f = [[False] * w for _ in range(h)] while len(d): (i, j) = d.popleft() if no...
# Question There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. Write a program to count the number of black tiles wh...
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column...
[ "class InputHandlerObject(object):\n\tinputs = []\n\n\tdef getInput(self, n=0):\n\t\tres = ''\n\t\tinputs = self.inputs\n\t\tif not inputs:\n\t\t\tinputs.extend(input().split(' '))\n\t\tif n == 0:\n\t\t\tres = inputs[:]\n\t\t\tinputs[:] = []\n\t\twhile n > len(inputs):\n\t\t\tinputs.extend(input().split(' '))\n\t\t...
{"inputs": ["4 23\n", "2 1\n", "33 1\n", "3 75\n", "77 93\n", "1 4\n", "7 14\n", "4 1\n", "2 11\n", "100 100\n", "77 20\n", "58 2\n", "30 31\n", "48 2\n", "48 24\n", "2 4\n", "3 1\n", "33 2\n", "3 57\n", "77 57\n", "1 3\n", "12 14\n", "8 1\n", "4 11\n", "59 20\n", "77 2\n", "43 31\n", "48 3\n", "47 24\n", "2 2\n", "33 ...
VERY_HARD
['probabilities', 'math', 'constructive algorithms']
null
codeforces
['Constructive algorithms', 'Mathematics', 'Probability']
[]
https://codeforces.com/problemset/problem/418/C
1.0 seconds
null
null
256.0 megabytes
null
25,353
0
class InputHandlerObject(object): inputs = [] def getInput(self, n=0): res = '' inputs = self.inputs if not inputs: inputs.extend(input().split(' ')) if n == 0: res = inputs[:] inputs[:] = [] while n > len(inputs): inputs.extend(input().split(' ')) if n > 0: res = inputs[:n] inputs[:n] ...
# Question While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and...
Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remix of this so...
[ "def song_decoder(song):\n\treturn ' '.join(song.replace('WUB', ' ').split())\n", "def song_decoder(song):\n\timport re\n\treturn re.sub('(WUB)+', ' ', song).strip()\n", "def song_decoder(song):\n\treturn ' '.join([a for a in song.split('WUB') if a])\n", "def song_decoder(song):\n\tlist = filter(lambda x: x !...
def song_decoder(song):
{"fn_name": "song_decoder", "inputs": [["AWUBBWUBC"], ["AWUBWUBWUBBWUBWUBWUBC"], ["WUBAWUBBWUBCWUB"], ["RWUBWUBWUBLWUB"], ["WUBJKDWUBWUBWBIRAQKFWUBWUBYEWUBWUBWUBWVWUBWUB"], ["WUBKSDHEMIXUJWUBWUBRWUBWUBWUBSWUBWUBWUBHWUBWUBWUB"], ["QWUBQQWUBWUBWUBIWUBWUBWWWUBWUBWUBJOPJPBRH"], ["WUBWUBOWUBWUBWUBIPVCQAFWYWUBWUBWUBQWUBWUBWU...
EASY
[]
null
codewars
[]
[]
https://www.codewars.com/kata/551dc350bf4e526099000ae5
null
null
null
null
null
25,354
0
def song_decoder(song): return ' '.join(song.replace('WUB', ' ').split())
# Question Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remi...
Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one. Vasya drew several distinct points with integer coordinates on a plane and then drew an...
[ "import sys\n\ndef cross(o, a, b):\n\treturn (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\nN = int(input())\nA = [None] * N\nfor i in range(N):\n\t(x, y) = map(int, sys.stdin.readline().split())\n\tA[i] = (x, y - x * x)\nA.sort()\nupper = []\nfor p in reversed(A):\n\twhile len(upper) >= 2 and cross...
{"inputs": ["1\n-751115 -925948\n", "1\n-751115 -1566406\n", "3\n-1 -1\n0 2\n1 0\n", "3\n0 -1\n0 2\n2 0\n", "1\n-751115 -2469241\n", "3\n-1 -1\n0 2\n2 0\n", "1\n-751115 -4760337\n", "1\n-751115 -4345366\n", "3\n0 -1\n0 2\n1 0\n", "1\n-751115 -8685961\n", "3\n0 -1\n0 2\n1 -1\n", "1\n-751115 -16747294\n", "3\n0 -1\n0 2\n...
VERY_HARD
['geometry']
null
codeforces
['Geometry']
[]
https://codeforces.com/problemset/problem/1143/F
1.0 seconds
null
null
256.0 megabytes
null
25,360
0
import sys def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) N = int(input()) A = [None] * N for i in range(N): (x, y) = map(int, sys.stdin.readline().split()) A[i] = (x, y - x * x) A.sort() upper = [] for p in reversed(A): while len(upper) >= 2 and cross(upper[-2], upper[-1]...
# Question Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one. Vasya drew several distinct points with integer coordinates on a plane and ...
Given N bits to an AND - Gate find the output that will be produced. AND - Gate Table: 1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0 Example 1: Input: N = 4 arr: 1 1 1 0 Output: 0 Explanation: 1 & 1 = 1 1 & 1 = 1 1 & 0 = 0 hence output is 0 Example 2: Input: N = 4 arr: 0 0 1 0 Output: 0 Explanation: 0 & 0 = 0 0 & 1 = 0 0 ...
[ "class Solution:\n\n\tdef andGate(self, arr, N):\n\t\tif 0 in arr:\n\t\t\treturn 0\n\t\treturn 1\n", "class Solution:\n\n\tdef andGate(self, arr, N):\n\t\tfor i in range(N):\n\t\t\tif arr[i] == 0:\n\t\t\t\treturn 0\n\t\treturn 1\n", "class Solution:\n\n\tdef andGate(self, arr, N):\n\t\toutput = 1\n\t\tfor item ...
#User function Template for python3 class Solution: def andGate (self, arr, N): # code here
{"inputs": ["N = 4\narr:1 1 1 0", "N = 4\narr:0 0 1 0"], "outputs": ["0", "0"]}
EASY
['Data Structures', 'Bit Magic']
null
geeksforgeeks
['Bit manipulation', 'Data structures']
['Bit manipulation', 'Data structures']
https://practice.geeksforgeeks.org/problems/the-and-gate1231/1
null
null
0
null
O(N)
25,361
0
class Solution: def andGate(self, arr, N): if 0 in arr: return 0 return 1
# Question Given N bits to an AND - Gate find the output that will be produced. AND - Gate Table: 1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0 Example 1: Input: N = 4 arr: 1 1 1 0 Output: 0 Explanation: 1 & 1 = 1 1 & 1 = 1 1 & 0 = 0 hence output is 0 Example 2: Input: N = 4 arr: 0 0 1 0 Output: 0 Explanation: 0 & 0 = 0 ...
# Valid HK Phone Number ## Overview In Hong Kong, a valid phone number has the format ```xxxx xxxx``` where ```x``` is a decimal digit (0-9). For example: ## Task Define two functions, ```isValidHKPhoneNumber``` and ```hasValidHKPhoneNumber```, that ```return```s whether a given string is a valid HK phone number a...
[ "import re\nHK_PHONE_NUMBER = '\\\\d{4} \\\\d{4}'\n\ndef is_valid_HK_phone_number(number):\n\treturn bool(re.match(HK_PHONE_NUMBER + '\\\\Z', number))\n\ndef has_valid_HK_phone_number(number):\n\treturn bool(re.search(HK_PHONE_NUMBER, number))\n", "from re import match, search\nis_valid_HK_phone_number = lambda n...
def is_valid_HK_phone_number(number):
{"fn_name": "is_valid_HK_phone_number", "inputs": [["1234 5678"], ["2359 1478"], ["85748475"], ["3857 4756"], ["sklfjsdklfjsf"], [" 1234 5678 "], ["abcd efgh"], ["9684 2396"], ["836g 2986"], ["0000 0000"], ["123456789"], [" 987 634 "], [" 6 "], ["8A65 2986"], ["8368 2aE6"], ["8c65 2i86"]], "outputs": [[tru...
EASY
['Regular Expressions', 'Fundamentals']
null
codewars
['Fundamentals']
[]
https://www.codewars.com/kata/56f54d45af5b1fec4b000cce
null
null
null
null
null
25,364
0
import re HK_PHONE_NUMBER = '\\d{4} \\d{4}' def is_valid_HK_phone_number(number): return bool(re.match(HK_PHONE_NUMBER + '\\Z', number)) def has_valid_HK_phone_number(number): return bool(re.search(HK_PHONE_NUMBER, number))
# Question # Valid HK Phone Number ## Overview In Hong Kong, a valid phone number has the format ```xxxx xxxx``` where ```x``` is a decimal digit (0-9). For example: ## Task Define two functions, ```isValidHKPhoneNumber``` and ```hasValidHKPhoneNumber```, that ```return```s whether a given string is a valid HK ph...
Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise. There are N...
[ "(l, n) = [int(item) for item in input().split()]\nright = []\nleft = []\nfor i in range(n):\n\ta = int(input())\n\tright.append(a)\n\tleft.append(l - a)\nleft.reverse()\nrsum = [0] * (n + 1)\nlsum = [0] * (n + 1)\nfor i in range(n):\n\trsum[i + 1] += rsum[i] + right[i]\n\tlsum[i + 1] += lsum[i] + left[i]\nans = ma...
{"inputs": ["314159265 7\n21662711\n77271666\n89022761\n156626166\n160332356\n166902656\n453863319", "6 6\n1\n2\n3\n6\n7\n9", "10 3\n2\n7\n17", "391985414 7\n21662711\n77271666\n89022761\n156626166\n160332356\n166902656\n453863319", "10 3\n2\n7\n20", "10 3\n2\n7\n29", "3 6\n1\n2\n3\n6\n7\n9", "10 3\n2\n7\n28", "6 6\n1\...
UNKNOWN_DIFFICULTY
[]
AtCoder Grand Contest 030 - Tree Burning
atcoder
[]
[]
null
2.0 seconds
null
null
1024.0 megabytes
null
25,358
0
(l, n) = [int(item) for item in input().split()] right = [] left = [] for i in range(n): a = int(input()) right.append(a) left.append(l - a) left.reverse() rsum = [0] * (n + 1) lsum = [0] * (n + 1) for i in range(n): rsum[i + 1] += rsum[i] + right[i] lsum[i + 1] += lsum[i] + left[i] ans = max(right[-1], left[-1]) ...
# Question Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise. ...
Like any good boss, the Chef has delegated all cooking jobs to his employees so he can take care of other tasks. Occasionally, one of the cooks needs a tool that is out of reach. In some of these cases, the cook cannot leave their workstation to get the tool because they have to closely watch their food. In such cases,...
[ "def dist(pos1: list, pos2: list) -> int:\n\treturn abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])\n\ndef list2bin(n: int, lst: list) -> str:\n\tnum = 0\n\tfor x in lst:\n\t\tnum += 1 << x\n\treturn f'{num:08b}'\n\ndef pos2str(pos: list) -> str:\n\treturn '--'.join(map(str, pos))\n\ndef min_chef(chefs: list, tools...
{"inputs": ["3\n2\n1 0 0 1\n0 0 1 1\n3\n0 3 0 1\n0 4 0 2\n0 5 0 3\n3\n0 1 0 2\n0 1 0 2\n0 1 0 2"], "outputs": ["4\n10\n6"]}
MEDIUM_HARD
['Algorithms', 'Cycles', 'Graph Algos', 'Hamiltonian Cycle', 'Dynamic Programming']
null
codechef
['Dynamic programming', 'Paths and circuits', 'Graph traversal', 'Graph algorithms']
['Dynamic programming']
https://www.codechef.com/problems/TOOLS
0.710216 seconds
2010-08-09
0
50000 bytes
null
25,369
0
def dist(pos1: list, pos2: list) -> int: return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) def list2bin(n: int, lst: list) -> str: num = 0 for x in lst: num += 1 << x return f'{num:08b}' def pos2str(pos: list) -> str: return '--'.join(map(str, pos)) def min_chef(chefs: list, tools: list, htools: list, re...
# Question Like any good boss, the Chef has delegated all cooking jobs to his employees so he can take care of other tasks. Occasionally, one of the cooks needs a tool that is out of reach. In some of these cases, the cook cannot leave their workstation to get the tool because they have to closely watch their food. In...
Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. MoJaK doesn't ...
[ "n = int(input())\np = lambda a, b: print(a + 1, b + 1)\nif n % 4 > 1:\n\tprint('NO')\nelse:\n\tprint('YES')\n\tfor i in range(n % 4, n, 4):\n\t\tfor x in range(2):\n\t\t\tfor j in range(i):\n\t\t\t\tp(j, i + 2 * x)\n\t\t\tp(i + 2 * x, i + 2 * x + 1)\n\t\t\tfor j in range(i, 0, -1):\n\t\t\t\tp(j - 1, i + 2 * x + 1)...
{"inputs": ["3\n", "1\n", "5\n", "6\n", "7\n", "8\n", "10\n", "766\n", "555\n", "999\n", "150\n", "899\n", "111\n", "2\n", "22\n", "695\n", "406\n", "219\n", "974\n", "431\n", "186\n", "75\n", "898\n", "731\n", "26\n", "551\n", "310\n", "843\n", "978\n", "319\n", "814\n", "147\n", "58\n", "831\n", "695\n", "766\n", "6\...
VERY_HARD
['constructive algorithms']
null
codeforces
['Constructive algorithms']
[]
https://codeforces.com/problemset/problem/804/E
null
2019-12-31
null
null
null
25,373
0
n = int(input()) p = lambda a, b: print(a + 1, b + 1) if n % 4 > 1: print('NO') else: print('YES') for i in range(n % 4, n, 4): for x in range(2): for j in range(i): p(j, i + 2 * x) p(i + 2 * x, i + 2 * x + 1) for j in range(i, 0, -1): p(j - 1, i + 2 * x + 1) p(i, i + 3) p(i + 1, i + 2) p(i,...
# Question Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. Mo...
In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of zabuton. Init...
[ "N = int(input())\nmen = []\nfor _ in range(N):\n\t(H, P) = map(int, input().split())\n\tmen.append((H, P, H + P))\nmen.sort(key=lambda x: x[2])\nmaxH = max(men)[0]\ninf = maxH + 1\ndp = [[-1] * (N + 1) for _ in range(N + 1)]\ndp[0][0] = 0\nfor i in range(1, N + 1):\n\t(h, p, a) = men[i - 1]\n\tfor j in range(1, N ...
{"inputs": ["3\n2 4\n3 1\n4 2", "10\n1 3\n8 4\n8 3\n10 1\n6 4\n2 3\n4 2\n9 2\n8 3\n0 1", "3\n0 2\n1 0\n3 4", "10\n1 3\n8 4\n8 3\n10 1\n12 4\n2 3\n4 2\n9 2\n8 3\n0 1", "10\n1 3\n0 4\n15 3\n10 1\n8 4\n2 3\n4 2\n9 1\n8 3\n0 1", "10\n2 3\n0 4\n15 3\n10 1\n8 4\n2 1\n4 2\n9 1\n8 0\n0 1", "10\n2 3\n0 0\n15 3\n10 1\n8 4\n2 1\n...
UNKNOWN_DIFFICULTY
[]
CODE FESTIVAL 2017 Final - Zabuton
atcoder
[]
[]
null
2.0 seconds
null
null
256.0 megabytes
null
25,370
0
N = int(input()) men = [] for _ in range(N): (H, P) = map(int, input().split()) men.append((H, P, H + P)) men.sort(key=lambda x: x[2]) maxH = max(men)[0] inf = maxH + 1 dp = [[-1] * (N + 1) for _ in range(N + 1)] dp[0][0] = 0 for i in range(1, N + 1): (h, p, a) = men[i - 1] for j in range(1, N + 1): if 0 <= dp[i ...
# Question In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of z...
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4 solve( [[10,-15],[-1,-3]] ) =...
[ "def solve(arr):\n\t(p, q) = (1, 1)\n\tfor k in arr:\n\t\t(x, y) = (max(k), min(k))\n\t\ta = p * x\n\t\tb = q * x\n\t\tc = p * y\n\t\td = q * y\n\t\tp = max(a, b, c, d)\n\t\tq = min(a, b, c, d)\n\treturn max(p, q)\n", "def solve(arr):\n\tresult = arr[0]\n\tfor number_array in range(1, len(arr)):\n\t\tresult = [x ...
def solve(arr):
{"fn_name": "solve", "inputs": [[[[1, 2], [3, 4]]], [[[10, -15], [-1, -3]]], [[[-1, 2, -3, 4], [1, -2, 3, -4]]], [[[-11, -6], [-20, -20], [18, -4], [-20, 1]]], [[[14, 2], [0, -16], [-12, -16]]], [[[-3, -4], [1, 2, -3]]], [[[-2, -15, -12, -8, -16], [-4, -15, -7], [-10, -5]]]], "outputs": [[8], [45], [12], [17600], [3584...
EASY
['Fundamentals']
null
codewars
['Fundamentals']
[]
https://www.codewars.com/kata/5d0365accfd09600130a00c9
null
null
null
null
null
25,374
0
def solve(arr): (p, q) = (1, 1) for k in arr: (x, y) = (max(k), min(k)) a = p * x b = q * x c = p * y d = q * y p = max(a, b, c, d) q = min(a, b, c, d) return max(p, q)
# Question In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4 solve( [[10,-15],...
Humpy, the little elephant, has his birthday coming up. He invited all his cousins but doesn’t know how many of them are really coming as some of them are having exams coming up. He will only get to know how many of them are coming on the day of his birthday. He ordered sugarcane for his party, of length L. Humpy’s m...
[ "from sys import stdin, stdout\nn = int(stdin.readline())\nwhile n:\n\tn -= 1\n\t(k, l, e) = map(int, stdin.readline().strip().split(' '))\n\ta = map(int, stdin.readline().strip().split(' '))\n\tx = float(l) / float(e + sum(a))\n\tif x - int(x):\n\t\tstdout.write('NO\\n')\n\telse:\n\t\tstdout.write('YES\\n')\n", ...
{"inputs": [["2", "4 10 2", "2 2 3 1", "4 12 3", "6 5 7 3"]], "outputs": [["YES", "NO"]]}
UNKNOWN_DIFFICULTY
[]
null
codechef
[]
[]
https://www.codechef.com/IC32016/problems/HBB
null
null
null
null
null
25,378
0
from sys import stdin, stdout n = int(stdin.readline()) while n: n -= 1 (k, l, e) = map(int, stdin.readline().strip().split(' ')) a = map(int, stdin.readline().strip().split(' ')) x = float(l) / float(e + sum(a)) if x - int(x): stdout.write('NO\n') else: stdout.write('YES\n')
# Question Humpy, the little elephant, has his birthday coming up. He invited all his cousins but doesn’t know how many of them are really coming as some of them are having exams coming up. He will only get to know how many of them are coming on the day of his birthday. He ordered sugarcane for his party, of length L...
# Introduction The Condi (Consecutive Digraphs) cipher was introduced by G4EGG (Wilfred Higginson) in 2011. The cipher preserves word divisions, and is simple to describe and encode, but it's surprisingly difficult to crack. # Encoding Algorithm The encoding steps are: - Start with an `initial key`, e.g. `cryptogra...
[ "LOWER = 'abcdefghijklmnopqrstuvwxyz'\n\ndef encode(message, key, shift, encode=True):\n\tkey = sorted(LOWER, key=f'{key}{LOWER}'.index)\n\tresult = []\n\tfor char in message:\n\t\tif char in key:\n\t\t\ti = key.index(char)\n\t\t\tchar = key[(i + shift) % 26]\n\t\t\tshift = i + 1 if encode else -(key.index(char) + ...
def encode(message, key, shift, encode=True):
{"fn_name": "encode", "inputs": [["on", "cryptogram", 10]], "outputs": [["jx"]]}
EASY
['Strings', 'Algorithms', 'Ciphers']
null
codewars
['String algorithms']
[]
https://www.codewars.com/kata/59bf6b73bf10a4c8e5000047
null
null
null
null
null
25,375
0
LOWER = 'abcdefghijklmnopqrstuvwxyz' def encode(message, key, shift, encode=True): key = sorted(LOWER, key=f'{key}{LOWER}'.index) result = [] for char in message: if char in key: i = key.index(char) char = key[(i + shift) % 26] shift = i + 1 if encode else -(key.index(char) + 1) result.append(char) re...
# Question # Introduction The Condi (Consecutive Digraphs) cipher was introduced by G4EGG (Wilfred Higginson) in 2011. The cipher preserves word divisions, and is simple to describe and encode, but it's surprisingly difficult to crack. # Encoding Algorithm The encoding steps are: - Start with an `initial key`, e.g...
You are given array nums of n length and an integer k .return the maximum number of consecutive 1's in the array if you can flip at most k 0's. Example: Input: n = 11 nums = [1,1,1,0,0,0,1,1,1,1,0] k = 2 Output: 6 Explanation: You can flip 2 0 and obtain [1,1,1,0,0,1,1,1,1,1,1] Your Task: You don't have to read input ...
[ "class Solution:\n\n\tdef longestOnes(self, n, arr, k):\n\t\t(left, right) = (0, 0)\n\t\tzero_count = 0\n\t\tmaxlen = 0\n\t\twhile right < n:\n\t\t\tif arr[right] == 1:\n\t\t\t\tright += 1\n\t\t\telif zero_count == k:\n\t\t\t\tzero_count -= 1 - arr[left]\n\t\t\t\tleft += 1\n\t\t\telse:\n\t\t\t\tzero_count += 1\n\t\...
#User function Template for python3 class Solution: def longestOnes(self, n, a, k): # Code here
{"inputs": ["n = 11\r\nnums = [1,1,1,0,0,0,1,1,1,1,0]\r\nk = 2"], "outputs": ["6"]}
MEDIUM
[]
null
geeksforgeeks
[]
[]
https://practice.geeksforgeeks.org/problems/maximum-consecutive-ones/1
null
null
0
null
O(n)
25,355
0
class Solution: def longestOnes(self, n, arr, k): (left, right) = (0, 0) zero_count = 0 maxlen = 0 while right < n: if arr[right] == 1: right += 1 elif zero_count == k: zero_count -= 1 - arr[left] left += 1 else: zero_count += 1 right += 1 maxlen = max(maxlen, right - left) r...
# Question You are given array nums of n length and an integer k .return the maximum number of consecutive 1's in the array if you can flip at most k 0's. Example: Input: n = 11 nums = [1,1,1,0,0,0,1,1,1,1,0] k = 2 Output: 6 Explanation: You can flip 2 0 and obtain [1,1,1,0,0,1,1,1,1,1,1] Your Task: You don't have to...
You are given a tree that is built in a following way: initially there is single vertex 1. All the other vertices are added one by one, from vertex 2 to vertex N, by connecting it to one of those that have been added before. You are to find the diameter of the tree after adding each vertex. Let the distance between ver...
[ "def update(M, level, u, v):\n\tlevel[u] = level[v] + 1\n\tM[u][0] = v\n\tfor j in range(1, 18):\n\t\tif M[u][j - 1]:\n\t\t\tM[u][j] = M[M[u][j - 1]][j - 1]\n\ndef LCA(M, level, u, v):\n\tif u == v:\n\t\treturn u\n\tif level[u] < level[v]:\n\t\t(u, v) = (v, u)\n\tfor i in range(17, -1, -1):\n\t\tif M[u][i] and leve...
{"inputs": ["2\n3\n1\n1\n5\n1\n2\n3\n3"], "outputs": ["1\n2\n1\n2\n3\n3"]}
VERY_HARD
['Algorithms', 'Segment Trees', 'Fenwick Trees', 'Lowest Common Ancestor', 'Advanced Data Structures', 'Graphs', 'Advanced Algorithms', 'Advanced Graph Algos', 'Advanced Tree Structures', 'HLD', 'Data Structures', 'Graph Algos', 'Trees']
null
codechef
['Graph algorithms', 'Range queries', 'Segment trees revisited', 'Tree algorithms', 'Data structures', 'Tree queries']
['Data structures', 'Range queries']
https://www.codechef.com/problems/RRTREE
2 seconds
2013-09-14
0
50000 bytes
null
25,382
0
def update(M, level, u, v): level[u] = level[v] + 1 M[u][0] = v for j in range(1, 18): if M[u][j - 1]: M[u][j] = M[M[u][j - 1]][j - 1] def LCA(M, level, u, v): if u == v: return u if level[u] < level[v]: (u, v) = (v, u) for i in range(17, -1, -1): if M[u][i] and level[M[u][i]] >= level[v]: u = M[u]...
# Question You are given a tree that is built in a following way: initially there is single vertex 1. All the other vertices are added one by one, from vertex 2 to vertex N, by connecting it to one of those that have been added before. You are to find the diameter of the tree after adding each vertex. Let the distance...
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them. Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and dif...
[ "def tle():\n\tk = 0\n\twhile k >= 0:\n\t\tk += 1\n\ndef quad(a, b, c):\n\tdisc = b ** 2 - 4 * a * c\n\tif disc < 0:\n\t\tdisc = 0\n\tdisc = disc ** 0.5\n\treturn ((-b + disc) / 2 / a, (-b - disc) / 2 / a)\nx = int(input())\ny = list(map(float, input().strip().split(' ')))\nz = list(map(float, input().strip().split...
{"inputs": ["2\n0.25 0.75\n0.75 0.25\n", "3\n0.125 0.25 0.625\n0.625 0.25 0.125\n", "10\n0.01 0.01 0.01 0.01 0.01 0.1 0.2 0.2 0.4 0.05\n1.0 0 0 0 0 0 0 0 0 0\n", "10\n0 0 0 0 0 0 0 0 0 1.0\n1.0 0 0 0 0 0 0 0 0 0\n", "1\n1.0\n1.0\n", "2\n0.00001 0.99999\n0.5 0.5\n", "3\n0.1 0.1 0.8\n0.6 0.2 0.2\n", "8\n0.09597231 0.1131...
VERY_HARD
['probabilities', 'math', 'implementation', 'dp']
null
codeforces
['Mathematics', 'Dynamic programming', 'Implementation', 'Probability']
['Dynamic programming']
https://codeforces.com/problemset/problem/641/D
null
2019-12-31
null
null
null
25,384
0
def tle(): k = 0 while k >= 0: k += 1 def quad(a, b, c): disc = b ** 2 - 4 * a * c if disc < 0: disc = 0 disc = disc ** 0.5 return ((-b + disc) / 2 / a, (-b - disc) / 2 / a) x = int(input()) y = list(map(float, input().strip().split(' '))) z = list(map(float, input().strip().split(' '))) py = [0, y[0]] for i...
# Question Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them. Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is...
```if-not:sql Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. ``` ```if:sql ## SQL Notes: You will be given a table, `numbers`, with one column `number`. Return a table with a column `is_even` containing "Even" or "Odd" ...
[ "def even_or_odd(number):\n\treturn 'Odd' if number % 2 else 'Even'\n", "def even_or_odd(number):\n\treturn ['Even', 'Odd'][number % 2]\n", "def even_or_odd(number):\n\tstatus = ''\n\tif number % 2 == 0:\n\t\tstatus = 'Even'\n\telse:\n\t\tstatus = 'Odd'\n\treturn status\n", "def even_or_odd(number):\n\treturn...
def even_or_odd(number):
{"fn_name": "even_or_odd", "inputs": [[2], [1], [0], [1545452], [7], [78], [17], [74156741], [100000], [-123], [-456]], "outputs": [["Even"], ["Odd"], ["Even"], ["Even"], ["Odd"], ["Even"], ["Odd"], ["Odd"], ["Even"], ["Odd"], ["Even"]]}
EASY
['Mathematics', 'Fundamentals']
null
codewars
['Fundamentals', 'Mathematics']
[]
https://www.codewars.com/kata/53da3dbb4a5168369a0000fe
null
null
null
null
null
25,366
0
def even_or_odd(number): return 'Odd' if number % 2 else 'Even'
# Question ```if-not:sql Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. ``` ```if:sql ## SQL Notes: You will be given a table, `numbers`, with one column `number`. Return a table with a column `is_even` containing "Eve...
You are given an array A consisting of N integers. In one operation, you can: Choose any two indices i and j (i \neq j); Subtract min(A_{i} , A_{j}) from both A_{i} and A_{j}. Note that min(A_{i} , A_{j}) denotes the minimum of A_{i} and A_{j}. Determine whether you can make all the elements of the array equal to zer...
[ "for _ in range(int(input())):\n\tn = int(input())\n\ta = [int(x) for x in input().split()]\n\tassert len(a) == n\n\tassert all((x > 0 for x in a))\n\tsm = sum(a)\n\tif sm % 2 != 0:\n\t\tprint(-1)\n\t\tcontinue\n\tps_sm = {0: []}\n\tfor (i, x) in enumerate(a):\n\t\tps_sm_new = ps_sm.copy()\n\t\tfor (v, indices) in ...
{"inputs": ["3\n2\n1 1 \n3 \n1 3 1\n4\n1 3 1 3\n"], "outputs": ["1\n1 2\n-1\n2\n1 3\n2 4"]}
VERY_HARD
['Algorithms', 'Dynamic Programming', 'Knapsack']
null
codechef
['Dynamic programming']
['Dynamic programming']
https://www.codechef.com/problems/MISREP
1 seconds
2023-01-21
0
50000 bytes
null
25,388
0
for _ in range(int(input())): n = int(input()) a = [int(x) for x in input().split()] assert len(a) == n assert all((x > 0 for x in a)) sm = sum(a) if sm % 2 != 0: print(-1) continue ps_sm = {0: []} for (i, x) in enumerate(a): ps_sm_new = ps_sm.copy() for (v, indices) in ps_sm.items(): if v + x not in...
# Question You are given an array A consisting of N integers. In one operation, you can: Choose any two indices i and j (i \neq j); Subtract min(A_{i} , A_{j}) from both A_{i} and A_{j}. Note that min(A_{i} , A_{j}) denotes the minimum of A_{i} and A_{j}. Determine whether you can make all the elements of the array ...
Ted$Ted$ loves prime numbers. One day he is playing a game called legendary$legendary$ with his girlfriend Robin$Robin$. Ted$Ted$ writes a number N$N$ on a table and the number is in the form of : N = P1A1 * P2A2 * ……….. * PnAn Ted$Ted$ asks Robin$Robin$ to find the sum of all the numbers which are less than or equal ...
[ "d = 10 ** 9 + 7\nt = int(input())\nwhile t:\n\tt -= 1\n\tn = int(input())\n\tp = list(map(int, input().strip().split()))\n\ta = list(map(int, input().strip().split()))\n\tb = list(map(int, input().strip().split()))\n\tans = 1\n\tfor i in range(n):\n\t\tc = a[i] - b[i] + 1\n\t\ttmp = pow(p[i], b[i], d) * ((pow(p[i]...
{"inputs": [["1", "3", "2 3 5", "2 1 2", "1 1 1"]], "outputs": [["540"]]}
UNKNOWN_DIFFICULTY
[]
null
codechef
[]
[]
https://www.codechef.com/AARA2018/problems/ARMBH4
null
null
null
null
null
25,390
0
d = 10 ** 9 + 7 t = int(input()) while t: t -= 1 n = int(input()) p = list(map(int, input().strip().split())) a = list(map(int, input().strip().split())) b = list(map(int, input().strip().split())) ans = 1 for i in range(n): c = a[i] - b[i] + 1 tmp = pow(p[i], b[i], d) * ((pow(p[i], c, d) - 1 + d) % d) * pow...
# Question Ted$Ted$ loves prime numbers. One day he is playing a game called legendary$legendary$ with his girlfriend Robin$Robin$. Ted$Ted$ writes a number N$N$ on a table and the number is in the form of : N = P1A1 * P2A2 * ……….. * PnAn Ted$Ted$ asks Robin$Robin$ to find the sum of all the numbers which are less th...
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $k$-th layer of the triangle contains $k$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $(r, c)$ ($1 \le c \le r...
[ "import os\nimport math\ntrue = True\nfalse = False\nfrom collections import defaultdict, deque, Counter\nfrom functools import reduce\nfrom heapq import *\nis_dev = 'vscode' in os.environ\nif is_dev:\n\tinF = open('in.txt', 'r')\n\toutF = open('out.txt', 'w')\n\ndef ins():\n\treturn list(map(int, input_().split(' ...
{"inputs": ["4\n3\n1 4 2\n1 3 1\n2\n2 4\n2 3\n2\n1 1000000000\n1 1000000000\n4\n3 10 5 8\n2 5 2 4\n", "4\n3\n1 4 2\n1 3 1\n2\n2 4\n2 3\n2\n1 1100000000\n1 1000000000\n4\n3 10 5 8\n2 5 2 4\n", "4\n3\n1 6 2\n1 3 1\n2\n2 4\n2 3\n2\n1 1100000000\n1 1000000000\n4\n3 10 5 8\n2 5 2 4\n", "4\n3\n1 4 2\n1 3 1\n2\n2 7\n2 3\n2\n1...
HARD
['math', 'shortest paths', 'graphs', 'sortings', 'constructive algorithms']
null
codeforces
['Graph algorithms', 'Shortest paths', 'Constructive algorithms', 'Sorting', 'Mathematics']
['Sorting']
https://codeforces.com/problemset/problem/1506/F
2 seconds
2021-03-25
1
256 megabytes
null
25,357
0
import os import math true = True false = False from collections import defaultdict, deque, Counter from functools import reduce from heapq import * is_dev = 'vscode' in os.environ if is_dev: inF = open('in.txt', 'r') outF = open('out.txt', 'w') def ins(): return list(map(int, input_().split(' '))) def inss(): re...
# Question Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $k$-th layer of the triangle contains $k$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $(r, c)$ ($1...
Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string ( A subsequence of a string is a new string which is formed from the original string by del...
[ "class Solution:\n\n\tdef isSubsequence(self, s, t):\n\t\tif len(s) > len(t):\n\t\t\treturn False\n\t\tfor i in s:\n\t\t\tif i in t:\n\t\t\t\tindex = t.find(i)\n\t\t\t\tt = t[index + 1:]\n\t\t\telse:\n\t\t\t\treturn False\n\t\treturn True\n", "class Solution:\n\n\tdef isSubsequence(self, s, t):\n\t\ti = 0\n\t\tif...
class Solution: def isSubsequence(self, s: str, t: str) -> bool:
{"fn_name": "isSubsequence", "inputs": [["\"abc\"", "\"ahbgdc\""]], "outputs": [true]}
MEDIUM_HARD
['Two Pointers', 'Dynamic Programming', 'String']
null
leetcode
['String algorithms', 'Dynamic programming', 'Amortized analysis']
['Dynamic programming', 'Amortized analysis']
https://leetcode.com/problems/is-subsequence/
null
null
null
null
null
25,392
0
class Solution: def isSubsequence(self, s, t): if len(s) > len(t): return False for i in s: if i in t: index = t.find(i) t = t[index + 1:] else: return False return True
# Question Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string ( A subsequence of a string is a new string which is formed from the original s...
We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i). Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there? We remind you that the distance between the origin and the point (p, q) can be represented as \sq...
[ "def main():\n\t(N, D) = [int(n) for n in input().split(' ')]\n\tcnt = 0\n\tfor i in range(N):\n\t\t(X, Y) = [int(x) for x in input().split(' ')]\n\t\tif X ** 2 + Y ** 2 <= D ** 2:\n\t\t\tcnt += 1\n\tprint(cnt)\nmain()\n", "(N, D) = map(int, input().split())\nxy = [list(map(int, input().split())) for i in range(N...
{"inputs": ["4 5\n0 5\n-2 4\n3 4\n4 -4\n", "12 3\n1 1\n1 1\n1 1\n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3\n", "20 100000\n14309 -32939\n-56855 100340\n151364 25430\n103789 -113141\n147404 -136977\n-37006 -30929\n188810 -49557\n13419 70401\n-88280 165170\n-196399 137941\n-176527 -61904\n46659 115261\n-153551 114185\n...
EASY
[]
null
atcoder
[]
[]
https://atcoder.jp/contests/abc174/tasks/abc174_b
null
null
null
null
null
25,379
0
def main(): (N, D) = [int(n) for n in input().split(' ')] cnt = 0 for i in range(N): (X, Y) = [int(x) for x in input().split(' ')] if X ** 2 + Y ** 2 <= D ** 2: cnt += 1 print(cnt) main()
# Question We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i). Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there? We remind you that the distance between the origin and the point (p, q) can be repres...
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function. ## Input The input for your function will be an array with a list of common duc...
[ "def create_report(names):\n\tresult = {}\n\tfor name in names:\n\t\tif name.startswith('Labrador Duck'):\n\t\t\treturn ['Disqualified data']\n\t\tname = name.upper().replace('-', ' ').split()\n\t\tcount = int(name.pop())\n\t\tif len(name) == 1:\n\t\t\tcode = name[0][:6]\n\t\telif len(name) == 2:\n\t\t\tcode = name...
def create_report(names):
{"fn_name": "create_report", "inputs": [[["Redhead 5", "Labrador Duck 9", "Blue-Winged Teal 25", "Steller's Eider 200"]], [["Canvasback 10", "Mallard 150", "American Wigeon 45", "Baikal Teal 3", "Barrow's Goldeneye 6", "Surf Scoter 12"]], [["Redhead 3", "Gadwall 1", "Smew 4", "Greater Scaup 10", "Redhead 3", "Ga...
EASY
['Regular Expressions', 'Arrays', 'Fundamentals', 'Data Science']
null
codewars
['Fundamentals', 'Data structures']
['Data structures']
https://www.codewars.com/kata/5b0737c724c0686bf8000172
null
null
null
null
null
25,393
0
def create_report(names): result = {} for name in names: if name.startswith('Labrador Duck'): return ['Disqualified data'] name = name.upper().replace('-', ' ').split() count = int(name.pop()) if len(name) == 1: code = name[0][:6] elif len(name) == 2: code = name[0][:3] + name[1][:3] elif len(nam...
# Question A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function. ## Input The input for your function will be an array with a list o...
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. [Image] The event coordinator has a list of k participants who should be picked up at the airport....
[ "k = int(input())\noutput = ['+------------------------+', '|#.#.#.#.#.#.#.#.#.#.#.|D|)', '|#.#.#.#.#.#.#.#.#.#.#.|.|', '|#.......................|', '|#.#.#.#.#.#.#.#.#.#.#.|.|)', '+------------------------+']\nls = [1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]...
{"inputs": ["9\n", "20\n", "30\n", "5\n", "0\n", "1\n", "2\n", "3\n", "4\n", "6\n", "7\n", "8\n", "10\n", "11\n", "12\n", "13\n", "14\n", "15\n", "16\n", "17\n", "18\n", "19\n", "21\n", "22\n", "23\n", "24\n", "25\n", "26\n", "27\n", "28\n", "29\n", "31\n", "32\n", "33\n", "34\n", "10\n", "18\n", "0\n", "23\n", "21\n",...
EASY
['implementation']
null
codeforces
['Implementation']
[]
https://codeforces.com/problemset/problem/475/A
null
2019-12-31
null
null
null
25,356
0
k = int(input()) output = ['+------------------------+', '|#.#.#.#.#.#.#.#.#.#.#.|D|)', '|#.#.#.#.#.#.#.#.#.#.#.|.|', '|#.......................|', '|#.#.#.#.#.#.#.#.#.#.#.|.|)', '+------------------------+'] ls = [1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4] t = k ...
# Question The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. [Image] The event coordinator has a list of k participants who should be picked up at ...
You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the s...
[ "def mergeSort(arr, n):\n\ttemp_arr = [0] * n\n\treturn _mergeSort(arr, temp_arr, 0, n - 1)\n\ndef _mergeSort(arr, temp_arr, left, right):\n\tinv_count = 0\n\tif left < right:\n\t\tmid = (left + right) // 2\n\t\tinv_count += _mergeSort(arr, temp_arr, left, mid)\n\t\tinv_count += _mergeSort(arr, temp_arr, mid + 1, r...
{"inputs": ["5\naaaza\n", "6\ncbaabc\n", "9\nicpcsguru\n", "50\nfhakqhdhrgfjruxndgfhdvcxhsrjfgdhsyrhfjcbfgdvrtdysf\n", "100\nzzzzzxxxyyyytttttssssssggggdddddjjjjjkkksssssjjjjrdddzzzzxxxxaaaaarrryjjjjddderehhhqazzzzzgdgseryydr\n", "2\ngg\n", "2\nzg\n", "5\nababa\n", "10\ndtottttotd\n", "11\nsssssssssss\n", "100\nrxxxrrx...
HARD
['data structures', 'greedy', 'strings']
null
codeforces
['String algorithms', 'Data structures', 'Greedy algorithms']
['Data structures', 'Greedy algorithms']
https://codeforces.com/problemset/problem/1430/E
2 seconds
2020-10-11
0
256 megabytes
null
25,362
0
def mergeSort(arr, n): temp_arr = [0] * n return _mergeSort(arr, temp_arr, 0, n - 1) def _mergeSort(arr, temp_arr, left, right): inv_count = 0 if left < right: mid = (left + right) // 2 inv_count += _mergeSort(arr, temp_arr, left, mid) inv_count += _mergeSort(arr, temp_arr, mid + 1, right) inv_count += mer...
# Question You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you shou...
Takahashi received otoshidama (New Year's money gifts) from N of his relatives. You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative. For example, if x_1 = 10000 and u_1 =...
[ "n = int(input())\nbtc = 380000.0\na = 0\nfor _ in range(n):\n\t(x, u) = input().split()\n\tif u == 'JPY':\n\t\ta += int(x)\n\telif u == 'BTC':\n\t\ta += float(x) * btc\nprint(a)\n", "n = int(input())\nans = 0\nb = 380000\nfor i in range(n):\n\t(x, u) = input().split()\n\tif u == 'JPY':\n\t\tans += int(x)\n\telse...
{"inputs": ["2\n10000 JPY\n0.10000000 BTC\n", "3\n100000000 JPY\n100.00000000 BTC\n0.00000001 BTC\n", "2\n0.00000001 BTC\n0.00000001 BTC\n", "10\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n100000000 JPY\n", "10\n100.00000000 BTC...
EASY
[]
AtCoder Beginner Contest 119 - Digital Gifts
atcoder
[]
[]
https://atcoder.jp/contests/abc119/tasks/abc119_b
2.0 seconds
null
null
1024.0 megabytes
null
25,367
0
n = int(input()) btc = 380000.0 a = 0 for _ in range(n): (x, u) = input().split() if u == 'JPY': a += int(x) elif u == 'BTC': a += float(x) * btc print(a)
# Question Takahashi received otoshidama (New Year's money gifts) from N of his relatives. You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative. For example, if x_1 = 100...
Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the a...
[ "class Solution:\n\n\tdef kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n\t\toneArrSum = sum(arr)\n\t\ttwoArr = arr + arr\n\n\t\tdef findMaxSub(array):\n\t\t\tif len(array) == 1:\n\t\t\t\treturn array[0]\n\t\t\tcur = 0\n\t\t\tsmall = 0\n\t\t\tret = -999999\n\t\t\tfor i in array:\n\t\t\t\tcur += i\n\t\t...
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
{"fn_name": "kConcatenationMaxSum", "inputs": [[[1, 2], 3]], "outputs": [9]}
MEDIUM
['Array', 'Dynamic Programming']
null
leetcode
['Dynamic programming', 'Data structures']
['Dynamic programming', 'Data structures']
https://leetcode.com/problems/k-concatenation-maximum-sum/
null
null
null
null
null
25,391
0
class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: oneArrSum = sum(arr) twoArr = arr + arr def findMaxSub(array): if len(array) == 1: return array[0] cur = 0 small = 0 ret = -999999 for i in array: cur += i small = cur if cur < small else small ret = c...
# Question Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is...
There is a one-dimensional garden of length N. In each position of the N length garden, a sprinkler has been installed. Given an array a[]such that a[i] describes the coverage limit of the i^{th} sprinkler. A sprinkler can cover the range from the position max(i - a[i], 1) to min(i + a[i], N). In beginning, all the spr...
[ "class Solution:\n\n\tdef minSprinkler(self, arr, N):\n\t\tcoverages = [-1] * N\n\t\tfor (i, a) in enumerate(arr):\n\t\t\tmin_coverage = max(0, i - a)\n\t\t\tmax_coverage = min(i + a, N - 1)\n\t\t\tcoverages[min_coverage] = max(coverages[min_coverage], max_coverage)\n\t\tneeded_sprinklers_count = 0\n\t\tcurrent_cov...
#User function Template for python3 class Solution(): def minSprinkler(self, arr, N): #your code goes here
{"inputs": ["a[] = {1, 2, 1}", "a[] = {2, 1, 1, 2, 1}"], "outputs": ["1", "2"]}
MEDIUM_HARD
[]
null
geeksforgeeks
[]
[]
https://practice.geeksforgeeks.org/problems/7645a18a9015b17f754b7a7e1c7d70825dde6acb/1
null
null
0
null
O(N)
25,397
0
class Solution: def minSprinkler(self, arr, N): coverages = [-1] * N for (i, a) in enumerate(arr): min_coverage = max(0, i - a) max_coverage = min(i + a, N - 1) coverages[min_coverage] = max(coverages[min_coverage], max_coverage) needed_sprinklers_count = 0 current_coverage = -1 next_max_coverage =...
# Question There is a one-dimensional garden of length N. In each position of the N length garden, a sprinkler has been installed. Given an array a[]such that a[i] describes the coverage limit of the i^{th} sprinkler. A sprinkler can cover the range from the position max(i - a[i], 1) to min(i + a[i], N). In beginning,...
You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game. The boss battle consists of $n$ turns. During each turn, you will get several cards. Each card has two parameters: its cost $c_i$ and damage $d_i$. You may play some of your cards during each ...
[ "from sys import stdin, stdout, exit\nn = int(input())\ninf = 10 ** 18\ndp = [[-inf] * 10 for i in range(n + 1)]\ndp[0][0] = 0\nfor i in range(n):\n\tk = int(stdin.readline())\n\tcards = []\n\tfor j in range(k):\n\t\t(c, d) = map(int, stdin.readline().split())\n\t\tcards.append((c, d))\n\tcards.sort(reverse=True)\n...
{"inputs": ["5\n3\n1 6\n1 7\n1 5\n2\n1 4\n1 3\n3\n1 10\n3 5\n2 3\n3\n1 15\n2 4\n1 10\n1\n1 100\n", "5\n3\n1 1\n1 1\n1 1\n3\n1 1\n1 1\n1 1\n3\n1 1\n1 1\n1 1\n3\n1 1\n1 1\n1 1\n3\n1 100\n1 1\n1 1\n", "1\n4\n1 1\n1 1\n2 2\n3 4\n", "5\n3\n1 1\n1 1\n1 1\n3\n1 1\n1 1\n1 1\n3\n1 1\n1 1\n1 1\n3\n1 1\n1 1\n1 1\n3\n1 100\n1 1\n1...
HARD
['sortings', 'implementation', 'dp']
null
codeforces
['Dynamic programming', 'Sorting', 'Implementation']
['Dynamic programming', 'Sorting']
https://codeforces.com/problemset/problem/1176/F
null
2019-12-31
null
null
null
25,401
0
from sys import stdin, stdout, exit n = int(input()) inf = 10 ** 18 dp = [[-inf] * 10 for i in range(n + 1)] dp[0][0] = 0 for i in range(n): k = int(stdin.readline()) cards = [] for j in range(k): (c, d) = map(int, stdin.readline().split()) cards.append((c, d)) cards.sort(reverse=True) cards_by_cost = [[] for ...
# Question You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game. The boss battle consists of $n$ turns. During each turn, you will get several cards. Each card has two parameters: its cost $c_i$ and damage $d_i$. You may play some of your cards ...
Singh is getting bored at work. He has a lot of ideas (N) to work on (as side projects) but is unable to choose one. He chooses a random number (R) and lines up his ideas in a circle. He starts counting from first and removes the R^th idea in the circle until only one remains. Help him choose an idea to work on. Inpu...
[ "N, R = [int(i) for i in input().split()]\n\nr = 0\nfor i in range(1, N+1):\n\tr = (r+R)%i\nprint(r+1)\n", "n,r = list(map(int, input().split()))\nm,j = n,0\nr -= 1\ntmp = [i+1 for i in range(n)]\nfor i in range(n):\n\tj = (j+r)%m\n\tans = tmp[j]\n\ttmp = tmp[:j]+tmp[j+1:]\n\tm -= 1\t\nprint(ans)\n", "n,k=list(...
{"inputs": ["23 9000001", "23 9000000"], "outputs": ["6", "4"]}
UNKNOWN_DIFFICULTY
[]
to-be-changed-choosing-a-project
hackerearth
[]
[]
null
null
null
null
null
null
25,412
0
N, R = [int(i) for i in input().split()] r = 0 for i in range(1, N+1): r = (r+R)%i print(r+1)
# Question Singh is getting bored at work. He has a lot of ideas (N) to work on (as side projects) but is unable to choose one. He chooses a random number (R) and lines up his ideas in a circle. He starts counting from first and removes the R^th idea in the circle until only one remains. Help him choose an idea to wo...
Given a triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` find the triangle's row knowing its index (the rows are 1-indexed), e.g.: ``` odd_row(1) == [1] odd_row(2) == [3, 5] odd_row(3) == [7, 9, 11] ``` **...
[ "odd_row = lambda n: list(range(n * (n - 1) + 1, n * (n + 1), 2))\n", "def odd_row(n):\n\tm = (n - 1) * n + 1\n\treturn [*range(m, m + n * 2, 2)]\n", "def odd_row(n):\n\treturn [x for x in range(n ** 2 - n + 1, (n + 1) ** 2 - n, 2)]\n", "def odd_row(n):\n\treturn [x for x in range(n * n - n, n * n + n) if x %...
def odd_row(n):
{"fn_name": "odd_row", "inputs": [[1], [2], [13], [19], [41], [93]], "outputs": [[[1]], [[3, 5]], [[157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181]], [[343, 345, 347, 349, 351, 353, 355, 357, 359, 361, 363, 365, 367, 369, 371, 373, 375, 377, 379]], [[1641, 1643, 1645, 1647, 1649, 1651, 1653, 1655, 1657...
EASY
['Performance', 'Algorithms']
null
codewars
[]
[]
https://www.codewars.com/kata/5d5a7525207a674b71aa25b5
null
null
null
null
null
25,405
0
odd_row = lambda n: list(range(n * (n - 1) + 1, n * (n + 1), 2))
# Question Given a triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` find the triangle's row knowing its index (the rows are 1-indexed), e.g.: ``` odd_row(1) == [1] odd_row(2) == [3, 5] odd_row(3) == [7, 9,...
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of ...
[ "t = int(input())\nfor _ in range(t):\n\tk = int(input())\n\tcount = 1\n\tfor _ in range(k):\n\t\toutput = []\n\t\tfor index in range(1, k + 1):\n\t\t\toutput.append(bin(count).replace('0b', ''))\n\t\t\tcount += 1\n\t\tprint(*output)\n", "for _ in range(int(input())):\n\tk = int(input())\n\tx = 1\n\tfor i in rang...
{"inputs": [["4", "1", "2", "3", "4"]], "outputs": [["1", "1 10", "11 100", "1 10 11", "100 101 110", "111 1000 1001", "1 10 11 100", "101 110 111 1000", "1001 1010 1011 1100", "1101 1110 1111 10000"]]}
UNKNOWN_DIFFICULTY
[]
null
codechef
[]
[]
https://www.codechef.com/PTRN2021/problems/ITGUY52
null
null
null
null
null
25,402
0
t = int(input()) for _ in range(t): k = int(input()) count = 1 for _ in range(k): output = [] for index in range(1, k + 1): output.append(bin(count).replace('0b', '')) count += 1 print(*output)
# Question The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a sin...
Read problems statements in Mandarin Chinese and Russian. This summer, there is a worldwide competition being held in Chef Town and some of the best chefs of the world are participating. The rules of this competition are quite simple. Each participant needs to bring his or her best dish. The judges will initially ...
[ "def find(child):\n\tnew_parent = child\n\twhile new_parent != parents[new_parent]:\n\t\tnew_parent = parents[new_parent]\n\twhile child != parents[child]:\n\t\ttemp = parents[child]\n\t\tparents[child] = new_parent\n\t\tchild = temp\n\treturn new_parent\n\ndef union(root1, root2):\n\t(real_root1, real_root2) = (fi...
{"inputs": ["1\n2\n1 2\n2\n0 1 2\n1 1", "1\n2\n1 3\n2\n0 1 2\n1 1", "1\n2\n1 1\n2\n0 1 2\n1 1", "1\n2\n1 3\n2\n0 1 1\n1 1", "1\n2\n0 1\n2\n0 2 2\n1 0", "1\n4\n0 1\n2\n0 2 2\n1 0", "1\n2\n0 1\n1\n0 1 1\n1 0", "1\n3\n0 1\n2\n0 1 2\n1 0", "1\n6\n0 1\n2\n0 1 2\n1 0", "1\n4\n0 1\n2\n0 1 2\n1 0", "1\n3\n0 1\n2\n0 1 1\n1 0", ...
MEDIUM_HARD
['Advanced Data Structures', 'Disjoint Set Union']
null
codechef
['Spanning trees', 'Data structures']
['Data structures']
https://www.codechef.com/problems/DISHOWN
0.5 seconds
2014-04-25
0
50000 bytes
null
25,399
0
def find(child): new_parent = child while new_parent != parents[new_parent]: new_parent = parents[new_parent] while child != parents[child]: temp = parents[child] parents[child] = new_parent child = temp return new_parent def union(root1, root2): (real_root1, real_root2) = (find(root1), find(root2)) if r...
# Question Read problems statements in Mandarin Chinese and Russian. This summer, there is a worldwide competition being held in Chef Town and some of the best chefs of the world are participating. The rules of this competition are quite simple. Each participant needs to bring his or her best dish. The judges wil...
Chef lives in a big apartment in Chefland. The apartment charges maintenance fees that he is supposed to pay monthly on time. But Chef is a lazy person and sometimes misses the deadlines. The apartment charges 1000 Rs per month as maintenance fees. Also, they also charge a one-time fine of 100 Rs for each of the late p...
[ "for i in range(int(input())):\n\tn = int(input())\n\tp = list(map(int, input().split()))\n\tamount = p.count(0) * 1000\n\tif p.count(0) != 0:\n\t\tq = p.index(0)\n\t\tprint(100 * (n - q) + amount)\n\telse:\n\t\tprint(amount)\n", "for _ in range(int(input())):\n\tn = int(input())\n\tl = list(map(int, input().spli...
{"inputs": [["4", "2", "1 1", "2", "0 0", "3", "0 1 0", "2", "0 1", "", ""]], "outputs": [["0", "2200", "2300", "1200"]]}
EASY
['Mathematics', 'Basic Maths']
null
codechef
['Mathematics']
[]
https://www.codechef.com/problems/CHEFAPAR
2 seconds
2017-02-01
0
50000 bytes
null
25,407
0
for i in range(int(input())): n = int(input()) p = list(map(int, input().split())) amount = p.count(0) * 1000 if p.count(0) != 0: q = p.index(0) print(100 * (n - q) + amount) else: print(amount)
# Question Chef lives in a big apartment in Chefland. The apartment charges maintenance fees that he is supposed to pay monthly on time. But Chef is a lazy person and sometimes misses the deadlines. The apartment charges 1000 Rs per month as maintenance fees. Also, they also charge a one-time fine of 100 Rs for each o...
Juggler Sequence is a series of integers in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation: Given a number N, find the Juggler Sequence for this number as the first term of the sequence. Example 1: I...
[ "import math\n\nclass Solution:\n\n\tdef jugglerSequence(self, N):\n\t\tif N == 1:\n\t\t\treturn [1]\n\t\tseq = [N]\n\t\tif N % 2 == 0:\n\t\t\tseq.extend(self.jugglerSequence(int(N ** 0.5)))\n\t\telse:\n\t\t\tseq.extend(self.jugglerSequence(int(N ** 1.5)))\n\t\treturn seq\n", "class Solution:\n\n\tdef jugglerSequ...
#User function Template for python3 class Solution: def jugglerSequence(self, N): # code here
{"inputs": ["N = 9", "N = 6"], "outputs": ["9 27 140 11 36 6 2 1", " 6 2 1"]}
EASY
['Recursion', 'Algorithms', 'Mathematical', 'series']
null
geeksforgeeks
['Mathematics', 'Complete search']
['Complete search']
https://practice.geeksforgeeks.org/problems/juggler-sequence3930/1
null
null
1
null
O(N)
25,398
0
import math class Solution: def jugglerSequence(self, N): if N == 1: return [1] seq = [N] if N % 2 == 0: seq.extend(self.jugglerSequence(int(N ** 0.5))) else: seq.extend(self.jugglerSequence(int(N ** 1.5))) return seq
# Question Juggler Sequence is a series of integers in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation: Given a number N, find the Juggler Sequence for this number as the first term of the sequence. ...
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square. You are to determine the minimum possible ...
[ "def min_squares(canvas, length, width):\n\n\tdef find_top():\n\t\tfor i in range(length):\n\t\t\tfor j in range(width):\n\t\t\t\tif canvas[i][j] == 'B':\n\t\t\t\t\treturn i\n\t\treturn -1\n\n\tdef find_left():\n\t\tfor j in range(width):\n\t\t\tfor i in range(length):\n\t\t\t\tif canvas[i][j] == 'B':\n\t\t\t\t\tre...
{"inputs": ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW\n", "1 2\nBB\n", "3 3\nWWW\nWWW\nWWW\n", "100 1\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nB\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\nW\...
EASY
['implementation']
null
codeforces
['Implementation']
[]
https://codeforces.com/problemset/problem/828/B
null
2019-12-31
null
null
null
25,395
0
def min_squares(canvas, length, width): def find_top(): for i in range(length): for j in range(width): if canvas[i][j] == 'B': return i return -1 def find_left(): for j in range(width): for i in range(length): if canvas[i][j] == 'B': return j def find_bottom(): for i in reversed(ra...
# Question Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square. You are to determine the minim...
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot...
[ "(X, n) = list(map(int, input().split()))\nTaken = [True] * (X + 1)\nfor i in range(n):\n\tx = list(map(int, input().split()))\n\tif x[0] == 1:\n\t\tTaken[x[1]] = False\n\t\tTaken[x[2]] = False\n\telse:\n\t\tTaken[x[1]] = False\ncnt = 0\nminn = 0\nmaxx = 0\nans = 0\nfor i in range(1, X):\n\tif Taken[i]:\n\t\tcnt +=...
{"inputs": ["3 2\n2 1\n2 2\n", "9 3\n1 2 3\n2 8\n1 4 5\n", "10 0\n", "10 2\n1 1 2\n1 8 9\n", "9 3\n1 4 5\n1 1 2\n1 6 7\n", "7 2\n2 3\n1 5 6\n", "81 28\n1 77 78\n1 50 51\n2 9\n1 66 67\n1 12 13\n1 20 21\n1 28 29\n1 34 35\n1 54 55\n2 19\n1 70 71\n1 45 46\n1 36 37\n2 47\n2 7\n2 76\n2 6\n2 31\n1 16 17\n1 4 5\n1 73 74\n1 64 ...
EASY
['greedy', 'math', 'implementation']
null
codeforces
['Mathematics', 'Implementation', 'Greedy algorithms']
['Greedy algorithms']
https://codeforces.com/problemset/problem/401/B
null
2019-12-31
null
null
null
25,406
0
(X, n) = list(map(int, input().split())) Taken = [True] * (X + 1) for i in range(n): x = list(map(int, input().split())) if x[0] == 1: Taken[x[1]] = False Taken[x[2]] = False else: Taken[x[1]] = False cnt = 0 minn = 0 maxx = 0 ans = 0 for i in range(1, X): if Taken[i]: cnt += 1 maxx += 1 else: ans += c...
# Question Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 ...
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).   Example 1: Input: text = "abcabcabc" Output: 3 Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab". Example 2: Input: ...
[ "from collections import defaultdict, deque\n\nclass Solution:\n\n\tdef distinctEchoSubstrings(self, text: str) -> int:\n\t\tif all((x == text[0] for x in text)):\n\t\t\treturn len(text) // 2\n\t\tres = set()\n\t\tcharacter_locations = defaultdict(lambda : deque())\n\t\tfor (i, c) in enumerate(text):\n\t\t\tfor j i...
class Solution: def distinctEchoSubstrings(self, text: str) -> int:
{"fn_name": "distinctEchoSubstrings", "inputs": [["\"abcabcabc\""]], "outputs": [3]}
MEDIUM
['Trie', 'Hash Function', 'Rolling Hash', 'String']
null
leetcode
['String algorithms']
[]
https://leetcode.com/problems/distinct-echo-substrings/
null
null
null
null
null
25,404
0
from collections import defaultdict, deque class Solution: def distinctEchoSubstrings(self, text: str) -> int: if all((x == text[0] for x in text)): return len(text) // 2 res = set() character_locations = defaultdict(lambda : deque()) for (i, c) in enumerate(text): for j in character_locations[c]: ...
# Question Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).   Example 1: Input: text = "abcabcabc" Output: 3 Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab". Exampl...
There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i. Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the ...
[ "import sys\ninput = sys.stdin.readline\nfrom collections import defaultdict\nn = int(input())\nabd = [list(map(int, input().split())) for i in range(n - 1)]\nif n == 2:\n\tprint(abd[0][2])\n\texit()\ngraph = [[] for i in range(n + 1)]\ndeg = [0 for i in range(n + 1)]\nfor (a, b, d) in abd:\n\tgraph[a].append((b, d...
{"inputs": ["8\n2 8 8\n1 5 1\n4 8 2\n2 5 4\n3 8 5\n6 8 9\n2 7 12", "5\n1 2 5\n3 4 10\n2 3 3\n2 5 2", "5\n1 3 5\n3 4 10\n2 3 3\n2 5 2", "5\n1 3 5\n2 4 20\n2 3 3\n2 5 2", "8\n2 8 8\n1 5 1\n4 8 2\n2 5 7\n3 8 6\n6 8 9\n2 7 12", "8\n2 8 8\n1 5 1\n4 8 0\n2 5 4\n3 8 5\n6 8 9\n2 7 12", "5\n1 3 4\n2 4 10\n2 3 3\n2 5 2", "8\n2 4...
UNKNOWN_DIFFICULTY
[]
AtCoder Grand Contest 018 - Tree and Hamilton Path
atcoder
[]
[]
null
2.0 seconds
null
null
256.0 megabytes
null
25,403
0
import sys input = sys.stdin.readline from collections import defaultdict n = int(input()) abd = [list(map(int, input().split())) for i in range(n - 1)] if n == 2: print(abd[0][2]) exit() graph = [[] for i in range(n + 1)] deg = [0 for i in range(n + 1)] for (a, b, d) in abd: graph[a].append((b, d)) graph[b].append...
# Question There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i. Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u a...
You are given $\textit{q}$ queries where each query consists of a set of $n$ points on a two-dimensional plane (i.e., $(x,y)$). For each set of points, print YES on a new line if all the points fall on the edges (i.e., sides and/or corners) of a non-degenerate rectangle which is axis parallel; otherwise, print NO inste...
[ "def main():\n\tfor i in range(int(input())):\n\t\tp = [list(map(int, input().split())) for j in range(int(input()))]\n\t\t(px, py) = zip(*p)\n\t\tx0 = min(px)\n\t\tx1 = max(px)\n\t\ty0 = min(py)\n\t\ty1 = max(py)\n\t\tresult = all((x in (x0, x1) or y in (y0, y1) for (x, y) in p))\n\t\tprint('YES' if result else 'N...
{"inputs": ["2\n3\n0 0\n0 1\n1 0\n4\n0 0\n0 2\n2 0\n1 1\n"], "outputs": ["YES\nNO\n"]}
EASY
['Mathematics - Geometry']
null
hackerrank
['Geometry']
[]
https://www.hackerrank.com/challenges/points-on-rectangle/problem
null
null
0
null
null
25,410
0
def main(): for i in range(int(input())): p = [list(map(int, input().split())) for j in range(int(input()))] (px, py) = zip(*p) x0 = min(px) x1 = max(px) y0 = min(py) y1 = max(py) result = all((x in (x0, x1) or y in (y0, y1) for (x, y) in p)) print('YES' if result else 'NO') main()
# Question You are given $\textit{q}$ queries where each query consists of a set of $n$ points on a two-dimensional plane (i.e., $(x,y)$). For each set of points, print YES on a new line if all the points fall on the edges (i.e., sides and/or corners) of a non-degenerate rectangle which is axis parallel; otherwise, pr...
Given a binary heap implementation of Priority Queue. Extract the maximum element from the queue i.e. remove it from the Queue and return it's value. Example 1: Input: 4 2 8 16 24 2 6 5 Output: 24 Priority Queue after extracting maximum: 16 8 6 5 2 2 4 Example 2: Input: 64 12 8 48 5 Output: 64 Priority Queue after e...
[ "class Solution:\n\n\tdef extractMax(self):\n\t\tglobal s\n\t\tans = H[0]\n\t\tH[0] = H[s]\n\t\ts -= 1\n\t\tshiftDown(0)\n\t\treturn ans\n" ]
#User function Template for python3 # 1. parent(i): Function to return the parent node of node i # 2. leftChild(i): Function to return index of the left child of node i # 3. rightChild(i): Function to return index of the right child of node i # 4. shiftUp(int i): Function to shift up the node in order to maintain...
{"inputs": ["4 2 8 16 24 2 6 5", "64 12 8 48 5"], "outputs": ["24", "64"]}
MEDIUM
[]
null
geeksforgeeks
[]
[]
https://practice.geeksforgeeks.org/problems/implementation-of-priority-queue-using-binary-heap/1
null
null
0
null
O(logN)
25,417
0
class Solution: def extractMax(self): global s ans = H[0] H[0] = H[s] s -= 1 shiftDown(0) return ans
# Question Given a binary heap implementation of Priority Queue. Extract the maximum element from the queue i.e. remove it from the Queue and return it's value. Example 1: Input: 4 2 8 16 24 2 6 5 Output: 24 Priority Queue after extracting maximum: 16 8 6 5 2 2 4 Example 2: Input: 64 12 8 48 5 Output: 64 Priority Q...
Rachel, being an awesome android programmer, just finished an App that will let us draw a triangle by selecting three points on the touch-plane.Now She asks her friend Bruce to draw a Right-Angled Triangle (we'll call it RAT) by selecting 3 integral points on the plane. A RAT is a triangle with Non-Zero area and a rig...
[ "def dist(x1,y1,x2,y2):\n\treturn (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)\n\ndef is_RAT(a):\n\tab = dist(a[0],a[1],a[2],a[3])\n\tbc = dist(a[4],a[5],a[2],a[3])\n\tca = dist(a[0],a[1],a[4],a[5])\n\tif ab == bc+ca or ca == bc+ab or bc == ab+ca:\n\t\treturn True\n\treturn False\t\ndef samepoint(a):\n\tif a[0]==a[2] and a[1] =...
{"inputs": ["20\n0 0 1 0 4 1\n0 0 1 0 100 1\n60 4 90 -53 32 -12\n52 -34 -37 -63 23 54\n39 22 95 25 42 -33\n-10 -11 62 6 -12 -3\n22 -15 -24 77 -69 -60\n99 85 90 87 64 -20\n-50 -37 -93 -6 -80 -80\n4 -13 4 -49 -24 -13\n0 -3 -3 -10 4 -7\n-45 -87 -34 -79 -60 -62\n-67 49 89 -76 -37 87\n22 32 -33 -30 -18 68\n36 1 -17 -54 -19 ...
UNKNOWN_DIFFICULTY
[]
autocorrect
hackerearth
[]
[]
null
null
null
null
null
null
25,415
0
def dist(x1,y1,x2,y2): return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2) def is_RAT(a): ab = dist(a[0],a[1],a[2],a[3]) bc = dist(a[4],a[5],a[2],a[3]) ca = dist(a[0],a[1],a[4],a[5]) if ab == bc+ca or ca == bc+ab or bc == ab+ca: return True return False def samepoint(a): if a[0]==a[2] and a[1] == a[3]: return True if ...
# Question Rachel, being an awesome android programmer, just finished an App that will let us draw a triangle by selecting three points on the touch-plane.Now She asks her friend Bruce to draw a Right-Angled Triangle (we'll call it RAT) by selecting 3 integral points on the plane. A RAT is a triangle with Non-Zero ar...
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the ar...
[ "n = int(input())\narr = [0]\narr = arr + list(map(int, input().split(' ')))\n\ndef getCounts(arr):\n\tlast = {}\n\tans = 0.0\n\tprev = 0.0\n\tres = 0.0\n\tfor i in range(1, len(arr)):\n\t\tif arr[i] not in last:\n\t\t\tans = prev + i\n\t\telse:\n\t\t\tans = prev + i - last[arr[i]]\n\t\tprev = ans\n\t\tres += ans\n...
{"inputs": ["2\n1 2\n", "2\n2 2\n", "10\n9 6 8 5 5 2 8 9 2 2\n", "20\n49 33 9 8 50 21 12 44 23 39 24 10 17 4 17 40 24 19 27 21\n", "1\n1000000\n", "10\n9 6 8 5 5 2 8 9 2 2\n", "20\n49 33 9 8 50 21 12 44 23 39 24 10 17 4 17 40 24 19 27 21\n", "1\n1000000\n", "10\n9 6 8 5 5 2 8 9 2 1\n", "20\n49 33 9 8 50 21 12 44 23 39 ...
MEDIUM_HARD
['two pointers', 'data structures', 'probabilities', 'math']
null
codeforces
['Data structures', 'Amortized analysis', 'Mathematics', 'Probability']
['Amortized analysis', 'Data structures']
https://codeforces.com/problemset/problem/846/F
null
2019-12-31
null
null
null
25,414
0
n = int(input()) arr = [0] arr = arr + list(map(int, input().split(' '))) def getCounts(arr): last = {} ans = 0.0 prev = 0.0 res = 0.0 for i in range(1, len(arr)): if arr[i] not in last: ans = prev + i else: ans = prev + i - last[arr[i]] prev = ans res += ans last[arr[i]] = i return res ans = (2 ...
# Question You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segme...
Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ elements are equal to $-1$. For each such array they counted its maximal pref...
[ "P = 998244853\nN = 4000\n(f, fi) = ([0] * (N + 1), [0] * (N + 1))\nf[0] = 1\nfor i in range(N):\n\tf[i + 1] = f[i] * (i + 1) % P\nfi[-1] = pow(f[-1], P - 2, P)\nfor i in reversed(range(N)):\n\tfi[i] = fi[i + 1] * (i + 1) % P\n\ndef C(n, r):\n\tc = 1\n\twhile n or r:\n\t\t(a, b) = (n % P, r % P)\n\t\tif a < b:\n\t\...
{"inputs": ["0 2\n", "2 0\n", "2 2\n", "2000 2000\n", "0 0\n", "11 2\n", "1 4\n", "5 13\n", "60 59\n", "27 16\n", "1134 1092\n", "756 1061\n", "953 1797\n", "76 850\n", "24 1508\n", "1087 1050\n", "149 821\n", "983 666\n", "45 1323\n", "1994 1981\n", "1942 1523\n", "1891 1294\n", "1132 1727\n", "1080 383\n", "1028 1040...
HARD
['number theory', 'combinatorics', 'math', 'dp']
null
codeforces
['Number theory', 'Combinatorics', 'Dynamic programming', 'Mathematics']
['Dynamic programming']
https://codeforces.com/problemset/problem/1204/E
null
2019-12-31
null
null
null
25,418
0
P = 998244853 N = 4000 (f, fi) = ([0] * (N + 1), [0] * (N + 1)) f[0] = 1 for i in range(N): f[i + 1] = f[i] * (i + 1) % P fi[-1] = pow(f[-1], P - 2, P) for i in reversed(range(N)): fi[i] = fi[i + 1] * (i + 1) % P def C(n, r): c = 1 while n or r: (a, b) = (n % P, r % P) if a < b: return 0 c = c * f[a] % P ...
# Question Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ elements are equal to $-1$. For each such array they counted its ...
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to ...
[ "import sys\nimport math\nMAXNUM = math.inf\nMINNUM = -1 * math.inf\nASCIILOWER = 97\nASCIIUPPER = 65\n\ndef getInt():\n\treturn int(sys.stdin.readline().rstrip())\n\ndef getInts():\n\treturn map(int, sys.stdin.readline().rstrip().split(' '))\n\ndef getString():\n\treturn sys.stdin.readline().rstrip()\n\ndef printO...
{"inputs": ["1 2\n", "2 3\n", "3 6\n", "10 1024\n", "10 577\n", "11 550\n", "19 12783\n", "28 72803174\n", "39 457181784666\n", "12 955\n", "13 154\n", "14 2334\n", "15 15512\n", "16 21395\n", "17 80239\n", "18 153276\n", "20 589266\n", "21 1687606\n", "24 14428281\n", "29 113463931\n", "1 1\n", "3 8\n", "31 1819651953...
MEDIUM_HARD
['trees', 'math', 'implementation']
null
codeforces
['Mathematics', 'Tree algorithms', 'Implementation']
[]
https://codeforces.com/problemset/problem/507/C
null
2019-12-31
null
null
null
25,400
0
import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(' ')) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout....
# Question Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from ...
Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical. Co...
[ "roll_dict = dict(E=(3, 1, 0, 5, 4, 2), W=(2, 1, 5, 0, 4, 3), S=(4, 0, 2, 3, 5, 1), N=(1, 5, 2, 3, 0, 4))\ndice1 = list(map(int, input().split()))\ndice2 = list(map(int, input().split()))\ndices = []\ndices.append(dice1)\njudge = False\nfor i in 'EWSN':\n\tdice = dices[0]\n\tnew_dice = []\n\tfor j in range(6):\n\t\...
{"inputs": ["1 2 3 2 5 6\n6 5 4 3 2 1", "1 2 3 2 5 6\n6 1 4 3 2 1", "1 2 3 2 5 6\n6 0 4 3 2 1", "1 2 3 2 5 6\n6 0 4 3 4 1", "1 2 3 2 7 6\n6 0 4 3 4 1", "1 2 3 2 7 3\n6 0 4 3 4 1", "1 2 2 2 7 6\n6 0 4 3 4 1", "1 2 2 2 7 9\n6 0 4 3 4 1", "1 2 2 2 7 9\n6 0 4 5 4 1", "1 0 2 2 7 9\n6 0 4 5 4 1", "2 0 2 2 7 9\n6 0 4 5 4 1", ...
UNKNOWN_DIFFICULTY
[]
null
aizu
[]
[]
null
1.0 seconds
null
null
134.217728 megabytes
null
25,376
0
roll_dict = dict(E=(3, 1, 0, 5, 4, 2), W=(2, 1, 5, 0, 4, 3), S=(4, 0, 2, 3, 5, 1), N=(1, 5, 2, 3, 0, 4)) dice1 = list(map(int, input().split())) dice2 = list(map(int, input().split())) dices = [] dices.append(dice1) judge = False for i in 'EWSN': dice = dices[0] new_dice = [] for j in range(6): new_dice.append(dic...
# Question Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as id...
*Words that contain many consecutive consonants, like "schtschurowskia", are generally considered somewhat hard to pronounce.* We say that a word is *hard to pronounce* if it contains 4 or more consonants in a row; otherwise it is *easy to pronounce*. For example, "apple" and "polish" are easy to pronounce, but "schts...
[ "for _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tif n <= 3:\n\t\tprint('YES')\n\telse:\n\t\tfor i in range(n - 3):\n\t\t\tstring = s[i:i + 4]\n\t\t\tvow1 = 'a' in string or 'e' in string or 'i' in string\n\t\t\tvow2 = 'o' in string or 'u' in string\n\t\t\tif not vow1 and (not vow2):\n\t\t\t\tpri...
{"inputs": ["5\n5\napple\n15\nschtschurowskia\n6\npolish\n5\ntryst\n3\ncry"], "outputs": ["YES\nNO\nYES\nNO\nYES\n"]}
EASY
['Data Structures', 'Basic Programming Concepts', 'Loops', 'String']
null
codechef
['String algorithms', 'Data structures']
['Data structures']
https://www.codechef.com/problems/EZSPEAK
1 seconds
2022-07-15
0
50000 bytes
null
25,411
0
for _ in range(int(input())): n = int(input()) s = input() if n <= 3: print('YES') else: for i in range(n - 3): string = s[i:i + 4] vow1 = 'a' in string or 'e' in string or 'i' in string vow2 = 'o' in string or 'u' in string if not vow1 and (not vow2): print('NO') break else: print('YES...
# Question *Words that contain many consecutive consonants, like "schtschurowskia", are generally considered somewhat hard to pronounce.* We say that a word is *hard to pronounce* if it contains 4 or more consonants in a row; otherwise it is *easy to pronounce*. For example, "apple" and "polish" are easy to pronounce...
You should write a simple function that takes string as input and checks if it is a valid Russian postal code, returning `true` or `false`. A valid postcode should be 6 digits with no white spaces, letters or other symbols. Empty string should also return false. Please also keep in mind that a valid post code **cann...
[ "def zipvalidate(postcode):\n\treturn len(postcode) == 6 and postcode.isdigit() and (postcode[0] not in '05789')\n", "import re\n\ndef zipvalidate(postcode):\n\treturn bool(re.fullmatch('[12346]\\\\d{5}', postcode))\n", "def zipvalidate(p):\n\treturn p.isdigit() and 100000 < int(p) < 699999 and (p[0] != '5')\n"...
def zipvalidate(postcode):
{"fn_name": "zipvalidate", "inputs": [["142784"], ["642784"], ["111"], ["1111111"], ["AA5590"], [""], ["\n245980"], ["245980\n"], ["245980a"], ["24598a"], [" 310587 "], ["555555"], ["775255"], ["875555"], ["012345"], ["968345"], ["@68345"]], "outputs": [[true], [true], [false], [false], [false], [false], [false], [fals...
EASY
['Regular Expressions', 'Fundamentals']
null
codewars
['Fundamentals']
[]
https://www.codewars.com/kata/552e45cc30b0dbd01100001a
null
null
null
null
null
25,421
0
def zipvalidate(postcode): return len(postcode) == 6 and postcode.isdigit() and (postcode[0] not in '05789')
# Question You should write a simple function that takes string as input and checks if it is a valid Russian postal code, returning `true` or `false`. A valid postcode should be 6 digits with no white spaces, letters or other symbols. Empty string should also return false. Please also keep in mind that a valid post...
Given a matrix Grid[][] of size NxN. Calculate the absolute difference between the sums of its diagonals. Example 1: Input: N=3 Grid=[[1,2,3],[4,5,6],[7,8,9]] Output: 0 Explanation: Sum of primary diagonal = 1+5+9 = 15. Sum of secondary diagonal = 3+5+7 = 15. Difference = |15 - 15| = 0. Example 2: Input: N=3 Grid=[[1,...
[ "class Solution:\n\n\tdef diagonalSumDifference(self, N, Grid):\n\t\t(Grid1, Grid2) = (0, 0)\n\t\tfor i in range(N):\n\t\t\tfor j in range(N):\n\t\t\t\tif i == j:\n\t\t\t\t\tGrid1 += Grid[i][j]\n\t\t\t\tif i + j == N - 1:\n\t\t\t\t\tGrid2 += Grid[i][j]\n\t\treturn abs(Grid1 - Grid2)\n", "class Solution:\n\n\tdef ...
#User function Template for python3 class Solution: def diagonalSumDifference(self,N,Grid): #code here
{"inputs": ["N=3\nGrid=[[1,2,3],[4,5,6],[7,8,9]]", "N=3\nGrid=[[1,1,1],[1,1,1],[1,1,1]]"], "outputs": ["0", "0"]}
EASY
['Data Structures', 'Matrix']
null
geeksforgeeks
['Matrices', 'Data structures']
['Data structures']
https://practice.geeksforgeeks.org/problems/find-difference-between-sum-of-diagonals1554/1
null
null
0
null
O(N)
25,419
0
class Solution: def diagonalSumDifference(self, N, Grid): (Grid1, Grid2) = (0, 0) for i in range(N): for j in range(N): if i == j: Grid1 += Grid[i][j] if i + j == N - 1: Grid2 += Grid[i][j] return abs(Grid1 - Grid2)
# Question Given a matrix Grid[][] of size NxN. Calculate the absolute difference between the sums of its diagonals. Example 1: Input: N=3 Grid=[[1,2,3],[4,5,6],[7,8,9]] Output: 0 Explanation: Sum of primary diagonal = 1+5+9 = 15. Sum of secondary diagonal = 3+5+7 = 15. Difference = |15 - 15| = 0. Example 2: Input: N...
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework. The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them...
[ "length = int(input())\nsequence = list(map(int, input().split()))\nif length <= 3:\n\tprint('no')\nelse:\n\tfor i in range(length - 1):\n\t\t(w, x) = sorted([sequence[i], sequence[i + 1]])\n\t\tfor j in range(length - 1):\n\t\t\t(y, z) = sorted([sequence[j], sequence[j + 1]])\n\t\t\tif w < y < x < z or y < w < z <...
{"inputs": ["4\n0 10 5 15\n", "4\n0 15 5 10\n", "5\n0 1000 2000 3000 1500\n", "5\n-724093 710736 -383722 -359011 439613\n", "50\n384672 661179 -775591 -989608 611120 442691 601796 502406 384323 -315945 -934146 873993 -156910 -94123 -930137 208544 816236 466922 473696 463604 794454 -872433 -149791 -858684 -467655 -55523...
MEDIUM
['brute force', 'implementation']
null
codeforces
['Implementation', 'Complete search']
['Complete search']
https://codeforces.com/problemset/problem/358/A
null
2019-12-31
null
null
null
25,413
0
length = int(input()) sequence = list(map(int, input().split())) if length <= 3: print('no') else: for i in range(length - 1): (w, x) = sorted([sequence[i], sequence[i + 1]]) for j in range(length - 1): (y, z) = sorted([sequence[j], sequence[j + 1]]) if w < y < x < z or y < w < z < x: print('yes') e...
# Question Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework. The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively ...
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height a_{i}. The Innopolis administration wants to build some houses on the hills. However, for the sake of city ap...
[ "from sys import stdin\nfrom math import ceil\nn = int(stdin.readline().strip())\ns = tuple([0] + list(map(int, stdin.readline().strip().split())) + [0])\nlim = ceil(n / 2) + 1\ndp = [[2000000002 for i in range(n + 1)] for j in range(lim)]\nvis = [[False for i in range(n + 1)] for j in range(lim)]\nfor i in range(n...
{"inputs": ["5\n1 1 1 1 1\n", "3\n1 2 3\n", "5\n1 2 3 2 2\n", "1\n10\n", "2\n1 100\n", "2\n2 2\n", "10\n2 2 4 4 3 1 1 2 3 2\n", "10\n32 48 20 20 15 2 11 5 10 34\n", "10\n99 62 10 47 53 9 83 33 15 24\n", "10\n1 2 3 4 5 6 7 8 9 10\n", "10\n5 1 6 2 8 3 4 10 9 7\n", "9\n1 100 1 100 1 100 1 100 1\n", "10\n8 9 7 6 3 2 3 2 2 ...
HARD
['dp']
null
codeforces
['Dynamic programming']
['Dynamic programming']
https://codeforces.com/problemset/problem/1012/C
null
2019-12-31
null
null
null
25,423
0
from sys import stdin from math import ceil n = int(stdin.readline().strip()) s = tuple([0] + list(map(int, stdin.readline().strip().split())) + [0]) lim = ceil(n / 2) + 1 dp = [[2000000002 for i in range(n + 1)] for j in range(lim)] vis = [[False for i in range(n + 1)] for j in range(lim)] for i in range(n + 1): dp[0...
# Question Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height a_{i}. The Innopolis administration wants to build some houses on the hills. However, for the sak...
Given two numbers A and B. Your task is to return the sum of A and B. Example 1: Input: A = 1, B = 2 Output: 3 Explanation: Addition of 1 and 2 is 3. Example 2: Input: A = 10, B = 20 Output: 30 Explanation: Addition os 10 and 20 is 30. Your Task: You don't need to read input or print anything. Your task is to com...
[ "class Solution:\n\n\tdef addition(ob, A, B):\n\t\treturn A + B\n", "class Solution:\n\n\tdef addition(ob, A, B):\n\t\tres = lambda x, y: x + y\n\t\treturn res(A, B)\n", "class Solution:\n\n\tdef addition(ob, A, B):\n\t\tc = int(A) + int(B)\n\t\treturn c\n", "class Solution:\n\n\tdef addition(ob, A, B):\n\t\t...
#User function Template for python3 class Solution: def addition (ob,A,B): # code here
{"inputs": ["A = 1, B = 2", "A = 10, B = 20"], "outputs": ["3", "30"]}
EASY
['Algorithms', 'CPP', 'Mathematical']
null
geeksforgeeks
['Mathematics']
[]
https://practice.geeksforgeeks.org/problems/addition-of-two-numbers0812/1
null
null
0
null
O(1)
25,424
0
class Solution: def addition(ob, A, B): return A + B
# Question Given two numbers A and B. Your task is to return the sum of A and B. Example 1: Input: A = 1, B = 2 Output: 3 Explanation: Addition of 1 and 2 is 3. Example 2: Input: A = 10, B = 20 Output: 30 Explanation: Addition os 10 and 20 is 30. Your Task: You don't need to read input or print anything. Your ta...
Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. Example 1: Input: n = 6 A[] = {16,17,4,3,5,2} Output: 17 5 2 Explanation: The first leade...
[ "class Solution:\n\n\tdef leaders(self, A, N):\n\t\tleaders = []\n\t\tmax_right = A[N - 1]\n\t\tleaders.append(max_right)\n\t\tfor i in range(N - 2, -1, -1):\n\t\t\tif A[i] >= max_right:\n\t\t\t\tleaders.append(A[i])\n\t\t\t\tmax_right = A[i]\n\t\tleaders.reverse()\n\t\treturn leaders\n", "class Solution:\n\n\tde...
class Solution: #Back-end complete function Template for Python 3 #Function to find the leaders in the array. def leaders(self, A, N): #Code here
{"inputs": ["n = 6\r\nA[] = {16,17,4,3,5,2}", "n = 5\r\nA[] = {1,2,3,4,0}"], "outputs": ["17 5 2", "4 0"]}
EASY
['Data Structures', 'Arrays']
null
geeksforgeeks
['Data structures']
['Data structures']
https://practice.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1
null
null
0
null
O(n)
25,420
0
class Solution: def leaders(self, A, N): leaders = [] max_right = A[N - 1] leaders.append(max_right) for i in range(N - 2, -1, -1): if A[i] >= max_right: leaders.append(A[i]) max_right = A[i] leaders.reverse() return leaders
# Question Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. Example 1: Input: n = 6 A[] = {16,17,4,3,5,2} Output: 17 5 2 Explanation: The...
Given a non-empty array of unique positive integers A, consider the following graph: There are A.length nodes, labelled A[0] to A[A.length - 1]; There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.   ...
[ "from collections import defaultdict\n\nclass Solution:\n\tMAXPRIME = 100001\n\tisPrime = [0 for _ in range(MAXPRIME + 1)]\n\tisPrime[0] = -1\n\tisPrime[1] = -1\n\tfor i in range(2, MAXPRIME):\n\t\tif isPrime[i] == 0:\n\t\t\tfor multiple in range(i * i, MAXPRIME + 1, i):\n\t\t\t\tif isPrime[multiple] == 0:\n\t\t\t\...
class Solution: def largestComponentSize(self, A: List[int]) -> int:
{"fn_name": "largestComponentSize", "inputs": [[[4, 6, 15, 35]]], "outputs": [4]}
MEDIUM
['Union Find', 'Math', 'Array']
null
leetcode
['Spanning trees', 'Data structures', 'Mathematics']
['Data structures']
https://leetcode.com/problems/largest-component-size-by-common-factor/
null
null
null
null
null
25,394
0
from collections import defaultdict class Solution: MAXPRIME = 100001 isPrime = [0 for _ in range(MAXPRIME + 1)] isPrime[0] = -1 isPrime[1] = -1 for i in range(2, MAXPRIME): if isPrime[i] == 0: for multiple in range(i * i, MAXPRIME + 1, i): if isPrime[multiple] == 0: isPrime[multiple] = i isPrime...
# Question Given a non-empty array of unique positive integers A, consider the following graph: There are A.length nodes, labelled A[0] to A[A.length - 1]; There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater than 1. Return the size of the largest connected component in t...
Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. Example 1: Input: Range = [-10, 13] Output: -8 6 7 13 Explanation: Nodes with values -13, 14 and 15 are outside the given range and hence are removed from the BST. This is ...
[ "class Solution:\n\n\tdef removekeys(self, root, l, r):\n\t\tif root is None:\n\t\t\treturn root\n\t\troot.left = self.removekeys(root.left, l, r)\n\t\troot.right = self.removekeys(root.right, l, r)\n\t\tif root.data > r:\n\t\t\treturn root.left\n\t\tif root.data < l:\n\t\t\treturn root.right\n\t\treturn root\n", ...
#User function Template for python3 ''' class Node: def __init__(self, val): self.right = None self.data = val self.left = None ''' class Solution: def removekeys(self, root, l, r): #code here
{"inputs": ["Range = [-10, 13]", "Range = [2, 6]\r\n 14\r\n / \\\r\n 4 16\r\n / \\ /\r\n 2 8 15\r\n / \\ / \\\r\n -8 3 7 10"], "outputs": ["-8 6 7 13", "2 3 4"]}
MEDIUM
['Data Structures', 'Binary Search Tree']
null
geeksforgeeks
['Data structures', 'Range queries']
['Data structures', 'Range queries']
https://practice.geeksforgeeks.org/problems/remove-bst-keys-outside-given-range/1
null
null
2
null
O(number of nodes)
25,426
0
class Solution: def removekeys(self, root, l, r): if root is None: return root root.left = self.removekeys(root.left, l, r) root.right = self.removekeys(root.right, l, r) if root.data > r: return root.left if root.data < l: return root.right return root
# Question Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. Example 1: Input: Range = [-10, 13] Output: -8 6 7 13 Explanation: Nodes with values -13, 14 and 15 are outside the given range and hence are removed from the B...
You are given two string S and T. Find the maximal length of some prefix of the string S which occurs in strings T as subsequence. Input The first line contains string S. The second line contains string T. Both strings consist of lowecase Latin letters. Output Output one integer - answer to the question. Constraints...
[ "\nfrom collections import deque, defaultdict, Counter\nfrom math import factorial\nfrom fractions import gcd\nfrom sys import stdin, exit\nfrom itertools import *\nimport heapq\nimport string\nimport re\n\n\ndef prase(T):\n\tif T == 1:\n\t\treturn list(map(int, testcase.next().strip().split()))\n\treturn testcase....
{"inputs": ["informatika\ninformatikainformatikainformatika\n", "qwertyuiopasdfghjklzxcvbnm\nmnbvcxzlkjhgfdsapoiuytrewq\n", "digger\nbiggerdiagram\n", "aaaaa\nkxqsrpzkxhzxvrglprtjjmukrzitcliouwjfjijwnuiwxqfiogfkxokxehdrihkoynezjddjkxwogyncwzhvhxqinmcdgrphmtxmogymewccrwtgucvicojcwvnxdcesjqdnddnsdutkxaaqrrtvifwjhxmwptscl...
EASY
['StringAlgorithms', 'Ad-Hoc']
prefpref
hackerearth
['String algorithms', 'Ad-hoc']
[]
null
null
null
null
null
null
25,429
0
from collections import deque, defaultdict, Counter from math import factorial from fractions import gcd from sys import stdin, exit from itertools import * import heapq import string import re def prase(T): if T == 1: return list(map(int, testcase.next().strip().split())) return testcase.next().strip().split() ...
# Question You are given two string S and T. Find the maximal length of some prefix of the string S which occurs in strings T as subsequence. Input The first line contains string S. The second line contains string T. Both strings consist of lowecase Latin letters. Output Output one integer - answer to the question. ...
Lia is fascinated by anything she considers to be a twin. She calls a pairs of positive integers, $\boldsymbol{i}$ and $j$, twins if: They are both prime. A prime number is an integer greater than $\mbox{1}$ that has no positive divisors other than $\mbox{1}$ and itself. Their absolute difference is exactly equal to ...
[ "limit = 1000000\n(beg, end) = map(int, input().strip().split(' '))\nis_prime = [False] * (limit + 1)\nprime = []\nfor x in range(1, int(limit ** 0.5) + 1):\n\tfor y in range(1, int(limit ** 0.5) + 1):\n\t\tn = 4 * x ** 2 + y ** 2\n\t\tif n <= limit and (n % 12 == 1 or n % 12 == 5):\n\t\t\tis_prime[n] = not is_prim...
{"inputs": ["3 13\n"], "outputs": ["3\n"]}
MEDIUM
['Mathematics - Number Theory']
null
hackerrank
['Number theory']
[]
https://www.hackerrank.com/challenges/twins/problem
null
null
0
null
null
25,425
0
limit = 1000000 (beg, end) = map(int, input().strip().split(' ')) is_prime = [False] * (limit + 1) prime = [] for x in range(1, int(limit ** 0.5) + 1): for y in range(1, int(limit ** 0.5) + 1): n = 4 * x ** 2 + y ** 2 if n <= limit and (n % 12 == 1 or n % 12 == 5): is_prime[n] = not is_prime[n] n = 3 * x ** 2...
# Question Lia is fascinated by anything she considers to be a twin. She calls a pairs of positive integers, $\boldsymbol{i}$ and $j$, twins if: They are both prime. A prime number is an integer greater than $\mbox{1}$ that has no positive divisors other than $\mbox{1}$ and itself. Their absolute difference is exact...
Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $n$ rows and $m$ columns. Let $(r, c)$ represent the cell in the $r$-th row and the $c$-th column. Initially, there are $k$ cards stacked in cell $(1, 1)$. Each card has an integer from $1$ to $k$ writ...
[ "import sys\ninput = sys.stdin.readline\n\ndef readList():\n\treturn list(map(int, input().split()))\n\ndef readInt():\n\treturn int(input())\n\ndef readInts():\n\treturn map(int, input().split())\n\ndef readStr():\n\treturn input().strip()\n\ndef solve():\n\t(n, m, k) = readInts()\n\tarr = readList()\n\tisPresent ...
{"inputs": ["4\n3 3 6\n3 6 4 1 2 5\n3 3 10\n1 2 3 4 5 6 7 8 9 10\n5 4 4\n2 1 3 4\n3 4 10\n10 4 9 3 5 6 8 2 7 1\n"], "outputs": ["YA\nTIDAK\nYA\nYA\n"]}
MEDIUM
['data structures', 'constructive algorithms']
null
codeforces
['Data structures', 'Constructive algorithms']
['Data structures']
https://codeforces.com/problemset/problem/1740/D
1 second
2022-10-29
1
256 megabytes
null
25,428
0
import sys input = sys.stdin.readline def readList(): return list(map(int, input().split())) def readInt(): return int(input()) def readInts(): return map(int, input().split()) def readStr(): return input().strip() def solve(): (n, m, k) = readInts() arr = readList() isPresent = [False] * (k + 1) curr = k ...
# Question Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $n$ rows and $m$ columns. Let $(r, c)$ represent the cell in the $r$-th row and the $c$-th column. Initially, there are $k$ cards stacked in cell $(1, 1)$. Each card has an integer from $1$...
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: the number of good substrings of even length; the number of good substrings...
[ "def R():\n\treturn map(int, input().split())\n\ndef I():\n\treturn int(input())\n\ndef S():\n\treturn str(input())\n\ndef L():\n\treturn list(R())\nfrom collections import Counter\nimport math\nimport sys\nfrom itertools import permutations\nimport bisect\nmod = 10 ** 9 + 7\ns = S()\nl = len(s)\nA = [0] * 2\nB = [...
{"inputs": ["bb\n", "baab\n", "babb\n", "babaa\n", "baabbbb\n", "babbbbbaaabaabbabbabbababbaaba\n", "baabaababaabbaabaaabbbaaaaaabbbabaaaabbbaaaaaaaaabbaabbbaabbaabbaabbababbbbbaaabbaabaaaaabaababbbbababaabaababbbaabbbaabbbbaaaabaabbbaabbbbbabbbabbabaaaabbbabbbaabaaaabbbbabbbababbabaaaabbabababbaaaaaabaabaaaaabbbbabbab...
HARD
['math']
null
codeforces
['Mathematics']
[]
https://codeforces.com/problemset/problem/451/D
null
2019-12-31
null
null
null
25,430
0
def R(): return map(int, input().split()) def I(): return int(input()) def S(): return str(input()) def L(): return list(R()) from collections import Counter import math import sys from itertools import permutations import bisect mod = 10 ** 9 + 7 s = S() l = len(s) A = [0] * 2 B = [0] * 2 for i in range(2): A[...
# Question We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: the number of good substrings of even length; the number of goo...
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** *the Nth smallest element in this array of integers* ___ # Notes * **_Array/list_** size is...
[ "def nth_smallest(arr, pos):\n\treturn sorted(arr)[pos - 1]\n", "from heapq import nsmallest\n\ndef nth_smallest(arr, pos):\n\treturn nsmallest(pos, arr)[-1]\n", "def nth_smallest(arr, pos):\n\tarr.sort()\n\treturn arr[pos - 1]\n", "import random\n\ndef quick_select(arr, pos):\n\tpivot = random.choice(arr)\n\...
def nth_smallest(arr, pos):
{"fn_name": "nth_smallest", "inputs": [[[3, 1, 2], 2], [[15, 20, 7, 10, 4, 3], 3], [[-5, -1, -6, -18], 4], [[-102, -16, -1, -2, -367, -9], 5], [[2, 169, 13, -5, 0, -1], 4]], "outputs": [[2], [7], [-1], [-2], [2]]}
EASY
['Arrays', 'Fundamentals']
null
codewars
['Fundamentals', 'Data structures']
['Data structures']
https://www.codewars.com/kata/5a512f6a80eba857280000fc
null
null
null
null
null
25,427
0
def nth_smallest(arr, pos): return sorted(arr)[pos - 1]
# Question # Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** *the Nth smallest element in this array of integers* ___ # Notes * **_Array/lis...
One day, Delta, the dog, got very angry. He has $N$ items with different values, and he decided to destroy a few of them. However, Delta loves his hooman as well. So he only destroyed those items whose Least Significant Bit in binary representation is 0. Can you help Delta to find the total damage he did so he could m...
[ "for test in range(int(input())):\n\tn = int(input())\n\tar = list(map(int, input().split()))\n\tcount = 0\n\tfor item in ar:\n\t\tif bin(item)[-1] == '0':\n\t\t\tcount += item\n\tprint(count)\n", "def bit(x):\n\ts = 0\n\tfor i in range(len(x)):\n\t\tp = bool(x[i] & 1 << 0)\n\t\tif p == False:\n\t\t\ts = s + x[i]...
{"inputs": [["1", "5", "1 2 3 4 5"]], "outputs": [["6"]]}
UNKNOWN_DIFFICULTY
[]
null
codechef
[]
[]
https://www.codechef.com/ENAU2020/problems/ECAUG202
null
null
null
null
null
25,433
0
for test in range(int(input())): n = int(input()) ar = list(map(int, input().split())) count = 0 for item in ar: if bin(item)[-1] == '0': count += item print(count)
# Question One day, Delta, the dog, got very angry. He has $N$ items with different values, and he decided to destroy a few of them. However, Delta loves his hooman as well. So he only destroyed those items whose Least Significant Bit in binary representation is 0. Can you help Delta to find the total damage he did s...
Chef's college is starting next week. There are $S$ subjects in total, and he needs to choose $K$ of them to attend each day, to fulfill the required number of credits to pass the semester. There are $N + 1$ buildings. His hostel is in building number $0$. Subject $i$ is taught in building $A_{i}$. After each subject, ...
[ "from collections import deque\n\ndef BFS(bldg, s):\n\tqueue = deque()\n\tqueue.append(s)\n\tcost = [-1 for i in range(n + 1)]\n\tcost[s] = 0\n\twhile queue:\n\t\ts = queue.popleft()\n\t\tfor i in bldg[s]:\n\t\t\tif cost[i] == -1:\n\t\t\t\tqueue.append(i)\n\t\t\t\tcost[i] = cost[s] + 1\n\treturn cost\nfor _ in rang...
{"inputs": ["3\n2 3 2 2\n0 1\n1 2\n2 0\n1 2\n2 2 2 2\n0 1\n1 2\n1 2\n6 7 5 3\n0 1\n0 2\n0 4\n1 3\n1 4\n2 5\n2 6\n1 2 3 5 6"], "outputs": ["4\n6\n8"]}
VERY_HARD
['Algorithms', 'Shortest Paths', 'BFS', 'Traversals', 'Graphs', "Dijkstra's Algorithm", 'Graph Algos', 'Data Structures']
null
codechef
['Data structures', 'Graph algorithms', 'Graph traversal', 'Shortest paths']
['Data structures']
https://www.codechef.com/problems/CLASSES
1 seconds
2020-12-30
0
50000 bytes
null
25,434
0
from collections import deque def BFS(bldg, s): queue = deque() queue.append(s) cost = [-1 for i in range(n + 1)] cost[s] = 0 while queue: s = queue.popleft() for i in bldg[s]: if cost[i] == -1: queue.append(i) cost[i] = cost[s] + 1 return cost for _ in range(int(input())): (n, m, s, k) = map(int...
# Question Chef's college is starting next week. There are $S$ subjects in total, and he needs to choose $K$ of them to attend each day, to fulfill the required number of credits to pass the semester. There are $N + 1$ buildings. His hostel is in building number $0$. Subject $i$ is taught in building $A_{i}$. After ea...
Given an array arr[ ] of size n such that elements of arr[ ] in range [0, 1, ..n-1]. Our task is to divide the array into the maximum number of partitions that can be sorted individually, then concatenated to make the whole array sorted. Example 1: ​Input : arr[ ] = {2, 1, 0, 3} Output : 2 Explanation: If divid...
[ "def maxPartitions(arr, n):\n\ta = arr[0]\n\tc = 0\n\tfor i in range(n):\n\t\tif a < arr[i]:\n\t\t\ta = arr[i]\n\t\tif a == i:\n\t\t\tc += 1\n\treturn c\n", "def maxPartitions(arr, n):\n\tmaxi = 0\n\tcount = 0\n\tfor (i, item) in enumerate(arr):\n\t\tmaxi = max(maxi, item)\n\t\tcount += maxi == i\n\treturn count\...
#User function Template for python3 def maxPartitions (arr, n) : #Complete the function
{"fn_name": "maxPartitions", "inputs": ["arr[ ] = {2, 1, 0, 3}", "arr[ ] = {2, 1, 0, 3, 4, 5}"], "outputs": ["2", "4"]}
EASY
['Data Structures', 'Arrays', 'Algorithms', 'Sorting']
null
geeksforgeeks
['Sorting', 'Data structures']
['Sorting', 'Data structures']
https://practice.geeksforgeeks.org/problems/maximum-number-of-partitions-that-can-be-sorted-individually-to-make-sorted2926/1
null
null
0
null
O(N).
25,435
0
def maxPartitions(arr, n): a = arr[0] c = 0 for i in range(n): if a < arr[i]: a = arr[i] if a == i: c += 1 return c
# Question Given an array arr[ ] of size n such that elements of arr[ ] in range [0, 1, ..n-1]. Our task is to divide the array into the maximum number of partitions that can be sorted individually, then concatenated to make the whole array sorted. Example 1: ​Input : arr[ ] = {2, 1, 0, 3} Output : 2 Explanati...
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule. A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form one...
[ "a = list(map(int, input().split()))\nif sum(a) % 2 == 1 or max(a) > sum(a) - max(a):\n\tprint('Impossible')\nelif len(set(a)) == 1:\n\tprint(a[0] // 2, a[0] // 2, a[0] // 2)\nelif a.count(min(a)) == 2:\n\tpos = a.index(max(a))\n\tans = [0] * 3\n\tans[pos] = ans[pos - 1] = max(a) // 2\n\tans[pos - 2] = (min(a) * 2 ...
{"inputs": ["1 1 2\n", "3 4 5\n", "4 1 1\n", "1 1 1\n", "1000000 1000000 1000000\n", "3 11 8\n", "8 5 12\n", "1000000 500000 1\n", "1000000 500000 2\n", "2 2 2\n", "3 3 3\n", "4 4 4\n", "2 4 2\n", "10 5 14\n", "10 5 15\n", "10 4 16\n", "3 3 6\n", "9 95 90\n", "3 5 8\n", "5 8 13\n", "6 1 5\n", "59 54 56\n", "246 137 940...
EASY
['brute force', 'graphs', 'math']
null
codeforces
['Graph algorithms', 'Mathematics', 'Complete search']
['Complete search']
https://codeforces.com/problemset/problem/344/B
null
2019-12-31
null
null
null
25,432
0
a = list(map(int, input().split())) if sum(a) % 2 == 1 or max(a) > sum(a) - max(a): print('Impossible') elif len(set(a)) == 1: print(a[0] // 2, a[0] // 2, a[0] // 2) elif a.count(min(a)) == 2: pos = a.index(max(a)) ans = [0] * 3 ans[pos] = ans[pos - 1] = max(a) // 2 ans[pos - 2] = (min(a) * 2 - max(a)) // 2 prin...
# Question Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule. A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom ...
A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one o...
[ "input()\nl1 = [int(x) for x in input().split() if x != '0']\nl2 = [int(x) for x in input().split() if x != '0']\nm = len(l1)\nx = l1.index(l2[0])\nb = True\nfor i in range(len(l1)):\n\tb &= l2[i] == l1[(x + i) % m]\nprint('YES' if b else 'NO')\n", "n = int(input())\na = list(map(int, input().split()))\nb = list(...
{"inputs": ["3\n1 0 2\n2 0 1\n", "2\n1 0\n0 1\n", "4\n1 2 3 0\n0 3 2 1\n", "9\n3 8 4 6 7 1 5 2 0\n6 4 8 5 3 1 2 0 7\n", "4\n2 3 1 0\n2 0 1 3\n", "4\n0 1 2 3\n2 0 1 3\n", "4\n3 0 1 2\n1 0 2 3\n", "3\n0 2 1\n1 2 0\n", "2\n0 1\n0 1\n", "6\n3 1 5 4 0 2\n0 4 3 5 2 1\n", "4\n2 0 3 1\n3 1 0 2\n", "5\n3 0 2 1 4\n4 3 0 1 2\n", ...
EASY
['implementation', 'constructive algorithms']
null
codeforces
['Implementation', 'Constructive algorithms']
[]
https://codeforces.com/problemset/problem/634/A
null
2019-12-31
null
null
null
25,436
0
input() l1 = [int(x) for x in input().split() if x != '0'] l2 = [int(x) for x in input().split() if x != '0'] m = len(l1) x = l1.index(l2[0]) b = True for i in range(len(l1)): b &= l2[i] == l1[(x + i) % m] print('YES' if b else 'NO')
# Question A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and a...
#Sorting on planet Twisted-3-7 There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference: #The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3. Your task is to create a method, that can sort an array the way it would be sor...
[ "def sort_twisted37(arr):\n\n\tdef key(x):\n\t\treturn int(str(x).translate(str.maketrans('37', '73')))\n\treturn sorted(arr, key=key)\n", "tr = str.maketrans('37', '73')\n\ndef sort_twisted37(arr):\n\treturn sorted(arr, key=lambda n: int(str(n).translate(tr)))\n", "def sort_twisted37(arr):\n\ttwisted = lambda ...
def sort_twisted37(arr):
{"fn_name": "sort_twisted37", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[12, 13, 14]], [[9, 2, 4, 7, 3]]], "outputs": [[[1, 2, 7, 4, 5, 6, 3, 8, 9]], [[12, 14, 13]], [[2, 7, 4, 3, 9]]]}
EASY
['Mathematics', 'Arrays', 'Algorithms', 'Sorting']
null
codewars
['Sorting', 'Data structures', 'Mathematics']
['Sorting', 'Data structures']
https://www.codewars.com/kata/58068479c27998b11900056e
null
null
null
null
null
25,440
0
def sort_twisted37(arr): def key(x): return int(str(x).translate(str.maketrans('37', '73'))) return sorted(arr, key=key)
# Question #Sorting on planet Twisted-3-7 There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference: #The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3. Your task is to create a method, that can sort an array the way it ...
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the s...
[ "from sys import stdin\ns = [ord(i) - 97 for i in stdin.readline().strip()]\ns1 = [ord(i) - 97 for i in stdin.readline().strip()]\nn = len(s)\nm = len(s1)\nmod = 1000000007\ndp = [[0 for i in range(n)] for j in range(26)]\nfor i in range(m):\n\tarr = [0 for j in range(n)]\n\tfor j in range(n):\n\t\tif s1[i] == s[j]...
{"inputs": ["bbabb\nbababbbbab\n", "ab\nbbbba\n", "xzzxxxzxzzzxzzzxxzzxzzxzxzxxzxxzxxzxzzxxzxxzxxxzxzxzxxzzxxxxzxzzzxxxzxzxxxzzxxzxxzxxzzxxzxxzxzxzzzxzzzzxzxxzzxzxxzxxzzxzxzx\nzzx\n", "a\nb\n", "zxzxzxzxzxzxzx\nd\n", "pfdempfohomnpgbeegikfmflnalbbajpnpgeacaicoehopgnabnklheepnlnflohjegcciflmfjhachnhekckfjgoffhkblncidn\n...
MEDIUM_HARD
['dp']
null
codeforces
['Dynamic programming']
['Dynamic programming']
https://codeforces.com/problemset/problem/163/A
2.0 seconds
null
null
256.0 megabytes
null
25,442
0
from sys import stdin s = [ord(i) - 97 for i in stdin.readline().strip()] s1 = [ord(i) - 97 for i in stdin.readline().strip()] n = len(s) m = len(s1) mod = 1000000007 dp = [[0 for i in range(n)] for j in range(26)] for i in range(m): arr = [0 for j in range(n)] for j in range(n): if s1[i] == s[j]: arr[j] = 1 ...
# Question One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x an...
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples. For example, tripl...
[ "import sys, os, io\n\ndef rs():\n\treturn sys.stdin.readline().rstrip()\n\ndef ri():\n\treturn int(sys.stdin.readline())\n\ndef ria():\n\treturn list(map(int, sys.stdin.readline().split()))\n\ndef ws(s):\n\tsys.stdout.write(s + '\\n')\n\ndef wi(n):\n\tsys.stdout.write(str(n) + '\\n')\n\ndef wia(a):\n\tsys.stdout.w...
{"inputs": ["3\n", "6\n", "1\n", "17\n", "67\n", "10\n", "14\n", "22\n", "23\n", "246\n", "902\n", "1000000000\n", "1998\n", "2222222\n", "2222226\n", "1111110\n", "9999998\n", "1024\n", "8388608\n", "4\n", "8\n", "16\n", "492\n", "493824\n", "493804\n", "493800\n", "2048\n", "8388612\n", "44\n", "444\n", "4444\n", "44...
MEDIUM
['number theory', 'math']
null
codeforces
['Number theory', 'Mathematics']
[]
https://codeforces.com/problemset/problem/707/C
null
2019-12-31
null
null
null
25,431
0
import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in ...
# Question Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples. For ex...
Given an integer, $n$, print the following values for each integer $\boldsymbol{i}$ from $\mbox{1}$ to $n$: Decimal Octal Hexadecimal (capitalized) Binary Function Description Complete the print_formatted function in the editor below. print_formatted has the following parameters: int number: the maximum v...
[ "N = int(input())\nwidth = len(str(bin(N))) - 2\nfor n in range(1, N + 1):\n\tfor base in 'doXb':\n\t\tprint('{0:{width}{base}}'.format(n, base=base, width=width), end=' ')\n\tprint()\n", "N = int(input())\npaddingLength = len(bin(N)[2:])\npadding = ' ' * paddingLength\nfor i in range(1, N + 1):\n\tprint(('{0:>' ...
{"inputs": ["17\n"], "outputs": [" 1 1 1 1\n 2 2 2 10\n 3 3 3 11\n 4 4 4 100\n 5 5 5 101\n 6 6 6 110\n 7 7 7 111\n 8 10 8 1000\n 9 11 9 1001\n 10 12 A 1010\n 11 13 B 1011\n 12 14...
EASY
['Python - Strings']
null
hackerrank
['String algorithms']
[]
https://www.hackerrank.com/challenges/python-string-formatting/problem
null
null
0
null
null
25,437
0
N = int(input()) width = len(str(bin(N))) - 2 for n in range(1, N + 1): for base in 'doXb': print('{0:{width}{base}}'.format(n, base=base, width=width), end=' ') print()
# Question Given an integer, $n$, print the following values for each integer $\boldsymbol{i}$ from $\mbox{1}$ to $n$: Decimal Octal Hexadecimal (capitalized) Binary Function Description Complete the print_formatted function in the editor below. print_formatted has the following parameters: int number: t...
You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \leq k \leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once. Let's consider all partitions of this permutation into $k$ disjoint segments. Formally, a partition is...
[ "(n, k) = [int(el) for el in input().split()]\nper = [int(el) for el in input().split()]\nsp = sorted(per, reverse=True)\nsp.append(0)\nmod = 998244353\nresult = 1\nprev = 0\nfor (i, p) in enumerate(per, 1):\n\tif p > sp[k]:\n\t\tif not prev:\n\t\t\tprev = i\n\t\telse:\n\t\t\tresult *= i - prev\n\t\t\tresult %= mod...
{"inputs": ["3 2\n2 1 3\n", "5 5\n2 1 5 3 4\n", "7 3\n2 7 3 1 5 4 6\n", "1 1\n1\n", "2 1\n1 2\n", "2 2\n2 1\n", "3 2\n3 2 1\n", "5 4\n2 1 3 5 4\n", "10 3\n4 6 7 8 9 1 10 3 5 2\n", "100 77\n59 92 18 16 45 82 63 43 50 68 19 13 53 79 48 28 94 49 25 77 54 8 61 66 40 100 99 20 35 14 52 56 22 17 57 36 23 90 4 65 84 42 30 27 ...
EASY
['greedy', 'combinatorics', 'math']
null
codeforces
['Combinatorics', 'Mathematics', 'Greedy algorithms']
['Greedy algorithms']
https://codeforces.com/problemset/problem/1326/C
1 second
2020-03-19
0
256 megabytes
null
25,409
0
(n, k) = [int(el) for el in input().split()] per = [int(el) for el in input().split()] sp = sorted(per, reverse=True) sp.append(0) mod = 998244353 result = 1 prev = 0 for (i, p) in enumerate(per, 1): if p > sp[k]: if not prev: prev = i else: result *= i - prev result %= mod prev = i print(sum(sp[:k]), ...
# Question You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \leq k \leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once. Let's consider all partitions of this permutation into $k$ disjoint segments. Formally, a ...
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ...
[ "(n, k) = map(int, input().split())\na = []\nb = []\nboth = []\nfor _ in range(n):\n\t(x, y, z) = map(int, input().split())\n\tif y == 1 and z == 1:\n\t\tboth.append(x)\n\telif y == 1:\n\t\ta.append(x)\n\telif z == 1:\n\t\tb.append(x)\na.sort()\nb.sort()\nfor i in range(min(len(a), len(b))):\n\tboth.append(a[i] + b...
{"inputs": ["8 4\n7 1 1\n2 1 1\n4 0 1\n8 1 1\n1 0 1\n1 1 1\n1 0 1\n3 0 0\n", "5 2\n6 0 0\n9 0 0\n1 0 1\n2 1 1\n5 1 0\n", "5 3\n3 0 0\n2 1 0\n3 1 0\n5 0 1\n3 0 1\n", "3 1\n3 0 1\n3 1 0\n3 0 0\n", "2 1\n7 1 1\n2 1 1\n", "5 1\n2 1 0\n2 0 1\n1 0 1\n1 1 0\n1 0 1\n", "6 3\n7 1 1\n8 0 0\n9 1 1\n6 1 0\n10 1 1\n5 0 0\n", "2 1\n...
MEDIUM_HARD
['data structures', 'greedy', 'sortings']
null
codeforces
['Sorting', 'Data structures', 'Greedy algorithms']
['Sorting', 'Data structures', 'Greedy algorithms']
https://codeforces.com/problemset/problem/1374/E1
2 seconds
2020-06-28
0
256 megabytes
null
25,387
0
(n, k) = map(int, input().split()) a = [] b = [] both = [] for _ in range(n): (x, y, z) = map(int, input().split()) if y == 1 and z == 1: both.append(x) elif y == 1: a.append(x) elif z == 1: b.append(x) a.sort() b.sort() for i in range(min(len(a), len(b))): both.append(a[i] + b[i]) both.sort() if len(both) <...
# Question Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice a...
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the...
[ "(n, x) = (int(input()), list(map(int, input().split(' '))))\ntmp = sorted(x, reverse=True)\nfor i in x:\n\tprint(tmp.index(i) + 1)\n", "n = int(input())\nl = list(map(int, input().split()))\npos = 1\nm = l[:]\nm.sort()\nm = m[::-1]\nres = []\nfor i in range(n):\n\tres.append(m.index(l[i]) + 1)\nfor j in res:\n\t...
{"inputs": ["8\n153 100 87 14 10 8 6 5\n", "70\n11 54 37 62 1 46 13 17 38 47 28 15 63 5 61 34 49 66 32 59 3 41 58 28 23 62 41 64 20 5 14 41 10 37 51 32 65 46 61 8 15 19 16 44 31 42 19 46 66 25 26 58 60 5 19 18 69 53 20 40 45 27 24 41 32 23 57 56 62 10\n", "11\n5 6 4 2 9 7 6 6 6 6 7\n", "2\n2000 2000\n", "3\n500 501 502...
EASY
['brute force', 'sortings', 'implementation']
null
codeforces
['Sorting', 'Implementation', 'Complete search']
['Sorting', 'Complete search']
https://codeforces.com/problemset/problem/551/A
2.0 seconds
null
null
256.0 megabytes
null
25,368
0
(n, x) = (int(input()), list(map(int, input().split(' ')))) tmp = sorted(x, reverse=True) for i in x: print(tmp.index(i) + 1)
# Question Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let'...
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two distinct str...
[ "t = int(input())\nfor x in range(t):\n\tn = int(input())\n\ts = input()\n\tt = input()\n\ti = c = 0\n\ta = b = ''\n\twhile c < 4 and i < n:\n\t\tif s[i] != t[i]:\n\t\t\tc += 1\n\t\t\ta += s[i]\n\t\t\tb += t[i]\n\t\ti += 1\n\tif c == 2 and len(set(a)) == len(set(b)) == 1:\n\t\tprint('Yes')\n\telse:\n\t\tprint('No')...
{"inputs": ["4\n5\nsouse\nhouhe\n3\ncat\ndog\n2\naa\naz\n3\nabc\nbca\n", "10\n11\nartiovnldnp\nartiovsldsp\n2\naa\nzz\n2\naa\nxy\n2\nab\nba\n2\nza\nzz\n3\nabc\nbca\n16\naajjhdsjfdsfkadf\naajjhjsjfdsfkajf\n2\nix\nii\n2\noo\nqo\n2\npp\npa\n", "1\n2\nab\ncd\n", "1\n4\naacd\nbbdc\n", "1\n4\naabb\ncccc\n", "1\n2\nab\ncc\n",...
EASY
['strings']
null
codeforces
['String algorithms']
[]
https://codeforces.com/problemset/problem/1243/B1
null
2019-12-31
null
null
null
25,408
0
t = int(input()) for x in range(t): n = int(input()) s = input() t = input() i = c = 0 a = b = '' while c < 4 and i < n: if s[i] != t[i]: c += 1 a += s[i] b += t[i] i += 1 if c == 2 and len(set(a)) == len(set(b)) == 1: print('Yes') else: print('No')
# Question This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two ...
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
[ "(M, N) = map(int, input().split())\nd = M * N // 2\nprint(d)\n", "a = list(map(int, input().split()))\na = a[1] * a[0]\nprint(a // 2)\n", "(M, N) = [int(x) for x in input().split()]\nq = N % 2\nw = N // 2\nif q == 0:\n\ts = w * M\nelse:\n\tc = M // 2\n\ts = c + w * M\nprint(s)\n", "(m, n) = map(int, input()....
{"inputs": ["2 6\n", "1 5\n", "3 6\n", "2 5\n", "3 16\n", "2 7\n", "3 10\n", "14 16\n", "1 16\n", "5 16\n", "4 4\n", "15 16\n", "5 7\n", "2 16\n", "2 2\n", "1 6\n", "1 1\n", "16 16\n", "14 15\n", "1 4\n", "2 14\n", "3 15\n", "2 3\n", "3 4\n", "11 13\n", "3 5\n", "3 14\n", "8 15\n", "15 15\n", "1 2\n", "1 15\n", "1 3\n"...
EASY
['greedy', 'math']
null
codeforces
['Mathematics', 'Greedy algorithms']
['Greedy algorithms']
https://codeforces.com/problemset/problem/50/A
2.0 seconds
null
null
256.0 megabytes
null
25,237
0
(M, N) = map(int, input().split()) d = M * N // 2 print(d)
# Question You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely cov...