problem_id
int64
2.36k
5k
question
stringlengths
52
14k
solutions
stringlengths
79
675k
input_output
stringlengths
37
505k
difficulty
stringclasses
1 value
url
stringlengths
36
94
starter_code
stringlengths
0
952
2,361
You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let th...
["from collections import defaultdict as dd\nfrom collections import deque\nimport bisect\nimport heapq\n\ndef ri():\n return int(input())\n\ndef rl():\n return list(map(int, input().split()))\n\n\ndef solve():\n n = ri()\n output = [0] * (n)\n\n Q = [(-n, 0 ,n - 1)]\n for i in range(1, n + 1):\n ...
{"inputs": ["6\n1\n2\n3\n4\n5\n6\n"], "outputs": ["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6 \n"]}
introductory
https://codeforces.com/problemset/problem/1353/D
2,362
$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the loc...
["def main():\n import sys\n input = sys.stdin.readline\n \n def solve():\n n = int(input())\n maxx = 10**5\n minx = -10**5\n maxy = 10**5\n miny = -10**5\n \n for _ in range(n):\n x, y, f1, f2, f3, f4 = map(int, input().split())\n if no...
{ "inputs": [ "4\n2\n-1 -2 0 0 0 0\n-1 -2 0 0 0 0\n3\n1 5 1 1 1 1\n2 5 0 1 0 1\n3 5 1 0 0 0\n2\n1337 1337 0 1 1 1\n1336 1337 1 1 0 1\n1\n3 5 1 1 1 1\n" ], "outputs": [ "1 -1 -2\n1 2 5\n0\n1 -100000 -100000\n" ] }
introductory
https://codeforces.com/problemset/problem/1196/C
2,363
There are $n$ athletes in front of you. Athletes are numbered from $1$ to $n$ from left to right. You know the strength of each athlete — the athlete number $i$ has the strength $s_i$. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team....
["\nT = int(input())\n\nfor _ in range(T):\n a = int(input())\n hh = sorted(map(int, input().split()))\n ans = 10**10\n for h1, h2 in zip(hh[:-1], hh[1:]):\n ans = min(ans, h2 - h1)\n\n print(ans)\n", "for u in range(int(input())):\n n=int(input())\n l=list(map(int,input().split()))\n l.s...
{ "inputs": [ "5\n5\n3 1 2 6 4\n6\n2 1 3 2 4 3\n4\n7 9 3 1\n2\n1 1000\n3\n100 150 200\n" ], "outputs": [ "1\n0\n2\n999\n50\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/B
2,364
You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) $a$ to the vertex (d...
["import sys\nfrom collections import deque\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n n, m, a, b, c = list(map(int,input().split()))\n p = list(map(int, input().split()))\n p.sort()\n \n pref = [0]\n curr = 0\n for i in range(m):\n curr += p[i]\n pref.appen...
{ "inputs": [ "2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7\n" ], "outputs": [ "7\n12\n" ] }
introductory
https://codeforces.com/problemset/problem/1343/E
2,365
We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you. For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p...
["import sys\ninput = sys.stdin.readline\n\ndef dfs(x,S):\n #print(x,S)\n for i in range(len(S)):\n if x in S[i]:\n S[i].remove(x)\n\n #print(x,S)\n \n LEN1=0\n for s in S:\n if len(s)==1:\n LEN1+=1\n ne=list(s)[0]\n if LEN1==2:\n re...
{ "inputs": [ "5\n6\n3 2 5 6\n2 4 6\n3 1 3 4\n2 1 3\n4 1 2 4 6\n5\n2 2 3\n2 1 2\n2 1 4\n2 4 5\n7\n3 1 2 6\n4 1 3 5 6\n2 1 2\n3 4 5 7\n6 1 2 3 4 5 6\n3 1 3 6\n2\n2 1 2\n5\n2 2 5\n3 2 3 5\n4 2 3 4 5\n5 1 2 3 4 5\n" ], "outputs": [ "3 1 4 6 2 5 \n3 2 1 4 5 \n2 1 6 3 5 4 7 \n1 2 \n2 5 3 4 1 \n" ] }
introductory
https://codeforces.com/problemset/problem/1343/F
2,366
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $n$ last days: $a_1, a_2, \dots, a_n$, where $a_i$ is the price of berPhone on the day $i$. Polycarp considers the price on the day $i$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For ...
["for _ in range(int(input())):\n n = int(input())\n A = list(map(int, input().split()))\n m = 10 ** 9\n c = 0\n for i in range(n - 1, -1, -1):\n if A[i] <= m:\n m = A[i]\n else:\n c += 1\n print(c)", "t = int(input())\nfor z in range(t):\n n = int(input())\n ...
{ "inputs": [ "5\n6\n3 9 4 6 7 5\n1\n1000000\n2\n2 1\n10\n31 41 59 26 53 58 97 93 23 84\n7\n3 2 1 2 3 4 5\n" ], "outputs": [ "3\n0\n1\n8\n2\n" ] }
introductory
https://codeforces.com/problemset/problem/1213/B
2,367
You are given two strings $s$ and $t$ both of length $n$ and both consisting of lowercase Latin letters. In one move, you can choose any length $len$ from $1$ to $n$ and perform the following operation: Choose any contiguous substring of the string $s$ of length $len$ and reverse it; at the same time choose any con...
["q = int(input())\nfor _ in range(q) :\n n = int(input())\n s = input()\n t = input()\n\n x = set(s)\n y = set(t)\n\n if x != y :\n print(\"NO\")\n continue\n\n if len(x) == n :\n a = [0] * n\n for i, c in enumerate(t) :\n a[i] = s.find(c)\n\n yeet = 0\n vis = [False] * n\n for i in ra...
{ "inputs": [ "4\n4\nabcd\nabdc\n5\nababa\nbaaba\n4\nasdf\nasdg\n4\nabcd\nbadc\n" ], "outputs": [ "NO\nYES\nNO\nYES\n" ] }
introductory
https://codeforces.com/problemset/problem/1256/F
2,368
You have $n$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $i$-th gift consists of $a_i$ candies and $b_i$ oranges. During one move, you can choose some gift $1 \le i \le n$ and do one of the following operations: ...
["t = int(input())\n\nfor _ in range(t):\n n = int(input())\n \n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n ma = min(a)\n mb = min(b)\n \n ops = 0\n for xa, xb in zip(a, b):\n da = xa - ma\n db = xb - mb\n ops += max(da, db)\n \n ...
{ "inputs": [ "5\n3\n3 5 6\n3 2 3\n5\n1 2 3 4 5\n5 4 3 2 1\n3\n1 1 1\n2 2 2\n6\n1 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1\n3\n10 12 8\n7 5 4\n" ], "outputs": [ "6\n16\n0\n4999999995\n7\n" ] }
introductory
https://codeforces.com/problemset/problem/1399/B
2,369
This problem is a version of problem D from the same contest with some additional constraints and tasks. There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of ea...
["# @author \n\nimport sys\n\nclass GCandyBoxHardVersion:\n def solve(self):\n q = int(input())\n for _ in range(q):\n n = int(input())\n a = [0] * n\n f = [0] * n\n for i in range(n):\n a[i], f[i] = [int(_) for _ in input().split()]\n\n ...
{ "inputs": [ "3\n8\n1 0\n4 1\n2 0\n4 1\n5 1\n6 1\n3 0\n2 0\n4\n1 1\n1 1\n2 1\n2 1\n9\n2 0\n2 0\n4 1\n4 1\n4 1\n7 0\n7 1\n7 0\n7 1\n" ], "outputs": [ "3 3\n3 3\n9 5\n" ] }
introductory
https://codeforces.com/problemset/problem/1183/G
2,370
The only difference between easy and hard versions is constraints. You are given a sequence $a$ consisting of $n$ positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\unde...
["#!usr/bin/env python3\nfrom collections import defaultdict, deque\nfrom heapq import heappush, heappop\nfrom itertools import permutations, accumulate\nimport sys\nimport math\nimport bisect\ndef LI(): return [int(x) for x in sys.stdin.readline().split()]\ndef I(): return int(sys.stdin.readline())\ndef LS():return [l...
{ "inputs": [ "6\n8\n1 1 2 2 3 2 1 1\n3\n1 3 3\n4\n1 10 10 1\n1\n26\n2\n2 1\n3\n1 1 1\n" ], "outputs": [ "7\n2\n4\n1\n1\n3\n" ] }
introductory
https://codeforces.com/problemset/problem/1335/E1
2,371
You are given an array $a$ consisting of $n$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $a$ to make it a good array. Recall that the prefix of the array $a=[a_1, a_2, \dots, a_n]$ is a subarray consisting several first elements: the prefix of the array $a$...
["for __ in range(int(input())):\n n = int(input())\n ar = list(map(int, input().split()))\n ar.reverse()\n ans = n - 1\n flag = False\n for i in range(1, n):\n if ar[i] < ar[i - 1]:\n flag = True\n if flag:\n if ar[i] > ar[i - 1]:\n break\n an...
{ "inputs": [ "5\n4\n1 2 3 4\n7\n4 3 3 8 4 5 2\n3\n1 1 1\n7\n1 3 1 4 5 3 2\n5\n5 4 3 2 3\n" ], "outputs": [ "0\n4\n0\n2\n3\n" ] }
introductory
https://codeforces.com/problemset/problem/1385/C
2,372
Initially, you have the array $a$ consisting of one element $1$ ($a = [1]$). In one move, you can do one of the following things: Increase some (single) element of $a$ by $1$ (choose some $i$ from $1$ to the current length of $a$ and increase $a_i$ by one); Append the copy of some (single) element of $a$ to the en...
["import math\nfor _ in range(int(input())):\n n=int(input())\n if n==1:\n print(0)\n else:\n k=int(n**(0.5))\n if k*k<n:\n k+=1\n # print(n,k) \n ans=k-1\n if k*(k-1)>=n:\n ans+=(k-2)\n else:\n ans+=(k-1)\n print(ans) ...
{ "inputs": [ "5\n1\n5\n42\n1337\n1000000000\n" ], "outputs": [ "0\n3\n11\n72\n63244\n" ] }
introductory
https://codeforces.com/problemset/problem/1426/C
2,373
You are given an array $a$ consisting of $n$ integers (it is guaranteed that $n$ is even, i.e. divisible by $2$). All $a_i$ does not exceed some integer $k$. Your task is to replace the minimum number of elements (replacement is the following operation: choose some index $i$ from $1$ to $n$ and replace $a_i$ with some...
["import sys\ndef input():\n\treturn sys.stdin.readline()[:-1]\n\nt = int(input())\nfor _ in range(t):\n\tn, k = map(int, input().split())\n\ta = list(map(int, input().split()))\n\tcum = [0 for _ in range(2*k+2)]\n\tfor i in range(n//2):\n\t\tx, y = a[i], a[n-i-1]\n\t\tcum[2] += 2\n\t\tcum[min(x, y)+1] -= 1\n\t\tcum[x+...
{ "inputs": [ "4\n4 2\n1 2 1 2\n4 3\n1 2 2 1\n8 7\n6 1 1 7 6 3 4 6\n6 6\n5 2 6 1 3 4\n" ], "outputs": [ "0\n1\n4\n2\n" ] }
introductory
https://codeforces.com/problemset/problem/1343/D
2,374
You are given a system of pipes. It consists of two rows, each row consists of $n$ pipes. The top left pipe has the coordinates $(1, 1)$ and the bottom right — $(2, n)$. There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: [Image] Types of ...
["ans = []\nfor _ in range(int(input())):\n n = int(input())\n s = list(input())\n t = list(input())\n lvl = 0\n X = [s, t]\n f = 1\n for i in range(n):\n if s[i] in '3456' and t[i] in '3456':\n lvl = 1 - lvl\n elif X[lvl][i] in '3456':\n f = 0\n ans.a...
{ "inputs": [ "6\n7\n2323216\n1615124\n1\n3\n4\n2\n13\n24\n2\n12\n34\n3\n536\n345\n2\n46\n54\n" ], "outputs": [ "YES\nYES\nYES\nNO\nYES\nNO\n" ] }
introductory
https://codeforces.com/problemset/problem/1234/C
2,375
The only difference between easy and hard versions is constraints. You are given a sequence $a$ consisting of $n$ positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\unde...
["from operator import itemgetter\nimport sys\ninput = sys.stdin.readline\n\nMAX_A = 200\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n \n ruiseki = [[0] * MAX_A for i in range(n + 1)]\n for i in range(n):\n for j in range(MAX_A):\n ru...
{ "inputs": [ "6\n8\n1 1 2 2 3 2 1 1\n3\n1 3 3\n4\n1 10 10 1\n1\n26\n2\n2 1\n3\n1 1 1\n" ], "outputs": [ "7\n2\n4\n1\n1\n3\n" ] }
introductory
https://codeforces.com/problemset/problem/1335/E2
2,376
You are given a tree (connected graph without cycles) consisting of $n$ vertices. The tree is unrooted — it is just a connected undirected graph without cycles. In one move, you can choose exactly $k$ leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove th...
["from bisect import bisect_left as bl\nfrom bisect import bisect_right as br\nfrom heapq import heappush,heappop,heapify\nimport math\nfrom collections import *\nfrom functools import reduce,cmp_to_key\nimport sys\ninput = sys.stdin.readline\nM = mod = 998244353\ndef factors(n):return sorted(set(reduce(list.__add__, (...
{ "inputs": [ "4\n8 3\n1 2\n1 5\n7 6\n6 8\n3 1\n6 4\n6 1\n10 3\n1 2\n1 10\n2 3\n1 5\n1 6\n2 4\n7 10\n10 9\n8 10\n7 2\n3 1\n4 5\n3 6\n7 4\n1 2\n1 4\n5 1\n1 2\n2 3\n4 3\n5 3\n" ], "outputs": [ "2\n3\n3\n4\n" ] }
introductory
https://codeforces.com/problemset/problem/1385/F
2,377
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on $n$ are less than in the hard version of the problem. You are given an array $a$ of $n$ integers (there are no equals elements in the array). You can perform the following operations on array ele...
["import sys\ninput = sys.stdin.readline\nimport bisect\n\nt=int(input())\nfor tests in range(t):\n n=int(input())\n A=list(map(int,input().split()))\n\n compression_dict={a: ind for ind, a in enumerate(sorted(set(A)))}\n A=[compression_dict[a] for a in A]\n\n Q=[0]*n\n \n for i in range(n):\n ...
{ "inputs": [ "4\n5\n4 7 2 3 9\n5\n3 5 8 1 7\n5\n1 4 5 7 12\n4\n0 2 1 3\n" ], "outputs": [ "2\n2\n0\n2\n" ] }
introductory
https://codeforces.com/problemset/problem/1367/F1
2,378
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $(0, 0)$ on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string $s$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $(x, y)$ right now, he can m...
["n = int(input())\nfor _ in range(n):\n s = input()\n l,r,u,d = [s.count(i) for i in 'LRUD']\n lr = min(l, r)\n ud = min(u, d)\n res = \"\"\n if lr == 0 and ud == 0:\n res = \"\"\n elif lr == 0:\n res = \"UD\"\n elif ud == 0:\n res = 'LR'\n else:\n res = 'R' * lr ...
{ "inputs": [ "6\nLRU\nDURLDRUDRULRDURDDL\nLRUDDLRUDRUL\nLLLLRRRR\nURDUR\nLLL\n" ], "outputs": [ "2\nLR\n14\nLLLUUUURRRDDDD\n12\nLLLUUURRRDDD\n2\nLR\n2\nUD\n0\n\n" ] }
introductory
https://codeforces.com/problemset/problem/1272/B
2,379
You are given a binary string $s$ consisting of $n$ zeros and ones. Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence shoul...
["import sys\n\ninput=sys.stdin.readline\n\n#t=1\nt=int(input())\nfor _ in range(t):\n n=int(input())\n s=input().rstrip()\n s=[s[-i-1] for i in range(n)]\n ans=[]\n zero=[]\n one=[]\n res=[-1]*n\n pos=0\n while s:\n b=s.pop()\n if b==\"0\":\n if not one:\n ...
{ "inputs": [ "4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000\n" ], "outputs": [ "2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4 \n" ] }
introductory
https://codeforces.com/problemset/problem/1399/D
2,380
You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$. In one move, you can choose one l...
["import sys\ninput = sys.stdin.readline\nrInt = lambda: int(input())\nmInt = lambda: map(int, input().split())\nrLis = lambda: list(map(int, input().split()))\n\nouts = []\n\nt = rInt()\nfor _ in range(t):\n n, k = mInt()\n s = input()\n\n pref = [0]\n for c in s:\n if c == '1':\n pref.ap...
{ "inputs": [ "6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0\n" ], "outputs": [ "1\n2\n5\n4\n0\n0\n" ] }
introductory
https://codeforces.com/problemset/problem/1353/E
2,381
There is a frog staying to the left of the string $s = s_1 s_2 \ldots s_n$ consisting of $n$ characters (to be more precise, the frog initially stays at the cell $0$). Each character of $s$ is either 'L' or 'R'. It means that if the frog is staying at the $i$-th cell and the $i$-th character is 'L', the frog can jump o...
["for i in range(int(input())):\n s='R' + input() + 'R'\n prev=0\n ma=-1\n for i in range(1,len(s)):\n if s[i]=='R':\n ma=max(ma,i-prev)\n prev=i\n print(ma) \n \n", "#!/usr/bin/env python3\nimport sys\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in ra...
{ "inputs": [ "6\nLRLRRLL\nL\nLLR\nRRRR\nLLLLLL\nR\n" ], "outputs": [ "3\n2\n3\n1\n7\n1\n" ] }
introductory
https://codeforces.com/problemset/problem/1324/C
2,382
You are given $n$ strings $a_1, a_2, \ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters. Find any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one...
["def isvalid(s):\n nonlocal l\n for i in l:\n count=0\n for j in range(len(i)):\n if(s[j]!=i[j]):\n count+=1\n if(count>1):\n return 0\n return 1\nt=int(input())\nfor you in range(t):\n l=input().split()\n n=int(l[0])\n m=int(l[1])\n l=[]\n...
{ "inputs": [ "5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc\n" ], "outputs": [ "zbac\n-1\naaa\nab\na\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/F
2,383
Find the minimum area of a square land on which you can place two identical rectangular $a \times b$ houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, You are given two identical rectangles with side lengths $a$ and $b$ ($1 \le a, b \le 100$) — positive integers (y...
["\nT = int(input())\n\nfor _ in range(T):\n a, b = list(map(int, input().split()))\n print(max(max(a, b), min(a, b) * 2)**2)\n", "from math import *\nimport math\n\ndef r1(t):\n return t(input())\n\ndef r2(t):\n return [t(i) for i in input().split()]\n\n\nfor zzz in range(r1(int)):\n a, b = r2(int)\n ...
{ "inputs": [ "8\n3 2\n4 2\n1 1\n3 1\n4 7\n1 3\n7 4\n100 100\n" ], "outputs": [ "16\n16\n4\n9\n64\n9\n64\n40000\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/A
2,384
This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $n$ are greater than in the easy version of the problem. You are given an array $a$ of $n$ integers (the given array can contain equal elements). You can perform the following operations on array e...
["from sys import stdin\nfor _ in range(int(input())):\n n = int(input())\n l = list(map(int,input().split()))\n id = list(zip(l,list(range(n))))\n id.sort()\n val, pos = zip(*id)\n blok = []\n cur = [pos[0]]\n for i in range(1,n):\n if val[i] == val[i-1]:\n cur.append(pos[i])\...
{ "inputs": [ "9\n5\n4 7 2 2 9\n5\n3 5 8 1 7\n5\n1 2 2 4 5\n2\n0 1\n3\n0 1 0\n4\n0 1 0 0\n4\n0 1 0 1\n4\n0 1 0 2\n20\n16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9\n" ], "outputs": [ "2\n2\n0\n0\n1\n1\n1\n1\n16\n" ] }
introductory
https://codeforces.com/problemset/problem/1367/F2
2,385
There is a rectangular grid of size $n \times m$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $(i, j)$ is $c_{i, j}$. You are also given a map of directions: for each cell, there is a direction $s_{i, j}$ which is one of the four characters 'U', 'R', 'D' and 'L'. If $s_{i, j}$ ...
["import sys\ninput = sys.stdin.readline\n\ndef search(i,j):\n L=[]\n\n c=0\n\n while CHECK[i][j]==1<<30:\n L.append((i,j))\n \n CHECK[i][j]=c\n\n if MAP2[i][j]==\"U\":\n i-=1\n elif MAP2[i][j]==\"D\":\n i+=1\n elif MAP2[i][j]==\"R\":\n ...
{ "inputs": [ "3\n1 2\n01\nRL\n3 3\n001\n101\n110\nRLL\nDLD\nULL\n3 3\n000\n000\n000\nRRD\nRLD\nULL\n" ], "outputs": [ "2 1\n4 3\n2 2\n" ] }
introductory
https://codeforces.com/problemset/problem/1335/F
2,386
A permutation of length $n$ is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ are permutations, and $[1, 1]$, $[0, 1]$, $[2, 2, 1, 4]$ are not. There was a permutation $p[1 \dots n]$. It was merged with itself. In other words...
["t = int(input())\n\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n print(*set(a))", "for _ in range(int(input())):\n n = int(input())\n a = list(map(int, input().split()))\n\n s = set()\n\n for el in a:\n len_before = len(s)\n s.add(el)\n\n if l...
{ "inputs": [ "5\n2\n1 1 2 2\n4\n1 3 1 4 3 4 2 2\n5\n1 2 1 2 3 4 3 5 4 5\n3\n1 2 3 1 2 3\n4\n2 3 2 4 1 3 4 1\n" ], "outputs": [ "1 2 \n1 3 4 2 \n1 2 3 4 5 \n1 2 3 \n2 3 4 1 \n" ] }
introductory
https://codeforces.com/problemset/problem/1385/B
2,387
Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burles as a c...
["import math\nfrom decimal import Decimal\nimport heapq\nimport copy\nimport heapq\nfrom collections import deque\ndef na():\n\tn = int(input())\n\tb = [int(x) for x in input().split()]\n\treturn n,b\n \n\t\ndef nab():\n\tn = int(input())\n\tb = [int(x) for x in input().split()]\n\tc = [int(x) for x in input().split()...
{ "inputs": [ "6\n1\n10\n19\n9876\n12345\n1000000000\n" ], "outputs": [ "1\n11\n21\n10973\n13716\n1111111111\n" ] }
introductory
https://codeforces.com/problemset/problem/1296/B
2,388
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most $\lfloor\frac{n}{2}\rfloor$ vertices in this graph so each unchosen vertex is adjacent (in other words, con...
["import sys\ninput = sys.stdin.readline\nT = int(input())\nfor _ in range(T):\n N, M = list(map(int, input().split()))\n E = [[] for aa in range(N)]\n for __ in range(M):\n a, b = list(map(int, input().split()))\n E[a-1].append(b-1)\n E[b-1].append(a-1)\n \n D = [-1] * N\n D[0] =...
{ "inputs": [ "2\n4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n6 8\n2 5\n5 4\n4 3\n4 1\n1 3\n2 3\n2 6\n5 6\n" ], "outputs": [ "1\n1 \n3\n3 4 6 \n" ] }
introductory
https://codeforces.com/problemset/problem/1176/E
2,389
The only difference between easy and hard versions is the size of the input. You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'. You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there ...
["from sys import stdin\nimport math\n\nrgb = 'RGB'\n\nfor query in range(int(stdin.readline())):\n n, k = list(map(int, stdin.readline().split()))\n s = stdin.readline()\n\n ans = math.inf\n for start in range(3):\n dp = [0 for i in range(n + 1)] \n for i in range(n):\n cur = rgb[(...
{ "inputs": [ "3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR\n" ], "outputs": [ "1\n0\n3\n" ] }
introductory
https://codeforces.com/problemset/problem/1196/D2
2,390
This problem is actually a subproblem of problem G from the same contest. There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift shou...
["import sys\ninput = sys.stdin.readline\n\nQ = int(input())\nfor _ in range(Q):\n N = int(input())\n A = [int(a) for a in input().split()]\n X = {}\n for a in A:\n if a in X:\n X[a] += 1\n else:\n X[a] = 1\n Y = []\n for x in X:\n Y.append(X[x])\n Y = sor...
{ "inputs": [ "3\n8\n1 4 8 4 5 6 3 8\n16\n2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1\n9\n2 2 4 4 4 7 7 7 7\n" ], "outputs": [ "3\n10\n9\n" ] }
introductory
https://codeforces.com/problemset/problem/1183/D
2,391
You are given an array $a$ consisting of $n$ integers. In one move, you can choose some index $i$ ($1 \le i \le n - 2$) and shift the segment $[a_i, a_{i + 1}, a_{i + 2}]$ cyclically to the right (i.e. replace the segment $[a_i, a_{i + 1}, a_{i + 2}]$ with $[a_{i + 2}, a_i, a_{i + 1}]$). Your task is to sort the ini...
["t = int(input())\nfor _ in range(t):\n n = int(input())\n l = list([int(x)- 1 for x in input().split()])\n out = []\n\n ll = [(l[i], i) for i in range(n)]\n ll.sort()\n\n swap = (-1,-1)\n for i in range(n - 1):\n if ll[i][0] == ll[i + 1][0]:\n swap = (ll[i][1],ll[i+1][1])\n\n ...
{"inputs": ["5\n5\n1 2 3 4 5\n5\n5 4 3 2 1\n8\n8 4 5 2 3 6 7 3\n7\n5 2 1 6 4 7 3\n6\n1 2 3 3 6 4\n"], "outputs": ["0\n\n6\n3 1 3 2 2 3 \n13\n2 1 1 6 4 2 4 3 3 4 4 6 6 \n-1\n4\n3 3 4 4 \n"]}
introductory
https://codeforces.com/problemset/problem/1374/F
2,392
Polycarp is reading a book consisting of $n$ pages numbered from $1$ to $n$. Every time he finishes the page with the number divisible by $m$, he writes down the last digit of this page number. For example, if $n=15$ and $m=5$, pages divisible by $m$ are $5, 10, 15$. Their last digits are $5, 0, 5$ correspondingly, the...
["for _ in range(int(input())):\n n, m = list(map(int, input().split()))\n A = []\n x = 1\n while True:\n if (m * x) % 10 not in A:\n A.append((m * x) % 10)\n else:\n break\n x += 1\n s = sum(A)\n n //= m\n print(s * (n // len(A)) + sum(A[:n % len(A)]))\n"...
{ "inputs": [ "7\n1 1\n10 1\n100 3\n1024 14\n998244353 1337\n123 144\n1234312817382646 13\n" ], "outputs": [ "1\n45\n153\n294\n3359835\n0\n427262129093995\n" ] }
introductory
https://codeforces.com/problemset/problem/1213/C
2,393
Polygon is not only the best platform for developing problems but also a square matrix with side $n$, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly...
["def read_int():\n return int(input())\n\n\ndef read_ints():\n return list(map(int, input().split(' ')))\n\n\nt = read_int()\nfor case_num in range(t):\n n = read_int()\n mat = []\n for i in range(n):\n mat.append(input())\n ok = True\n for i in range(n):\n for j in range(n):\n ...
{ "inputs": [ "5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111\n" ], "outputs": [ "YES\nNO\nYES\nYES\nNO\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/E
2,394
You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. yo...
["for _ in range(int(input())):\n n = int(input())\n s = input()\n st = 0\n fans = 0\n for x in s:\n if x == ')':\n st -= 1\n else:\n st += 1\n if st < 0:\n fans += 1\n st = 0\n print(fans)", "import sys\n# sys.setrecursionlimit(10**6) \...
{ "inputs": [ "4\n2\n)(\n4\n()()\n8\n())()()(\n10\n)))((((())\n" ], "outputs": [ "1\n0\n1\n3\n" ] }
introductory
https://codeforces.com/problemset/problem/1374/C
2,395
A number is ternary if it contains only digits $0$, $1$ and $2$. For example, the following numbers are ternary: $1022$, $11$, $21$, $2002$. You are given a long ternary number $x$. The first (leftmost) digit of $x$ is guaranteed to be $2$, the other digits of $x$ can be $0$, $1$ or $2$. Let's define the ternary XOR ...
["for _ in range(int(input())):\n n=int(input())\n s=input()\n a=\"\"\n b=\"\"\n flag=1\n for i in s:\n if flag:\n if i==\"2\":\n a+=\"1\"\n b+=\"1\"\n elif i==\"1\":\n a+=\"1\"\n b+=\"0\"\n flag=0\...
{ "inputs": [ "4\n5\n22222\n5\n21211\n1\n2\n9\n220222021\n" ], "outputs": [ "11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010\n" ] }
introductory
https://codeforces.com/problemset/problem/1328/C
2,396
You are given a string $s[1 \dots n]$ consisting of lowercase Latin letters. It is guaranteed that $n = 2^k$ for some integer $k \ge 0$. The string $s[1 \dots n]$ is called $c$-good if at least one of the following three conditions is satisfied: The length of $s$ is $1$, and it consists of the character $c$ (i.e. $s_...
["# coding: utf-8\n# Your code here!\n\ndef solve(s, c):\n if(len(s)==1):\n if s[0]==c:\n return 0\n else:\n return 1\n ans1 = sum([i!=c for i in s[:len(s)//2]]) + solve(s[len(s)//2:],chr(ord(c)+1))\n ans2 = sum([i!=c for i in s[len(s)//2:]]) + solve(s[:len(s)//2],chr(ord(c)...
{ "inputs": [ "6\n8\nbbdcaaaa\n8\nasdfghjk\n8\nceaaaabb\n8\nbbaaddcc\n1\nz\n2\nac\n" ], "outputs": [ "0\n7\n4\n5\n1\n1\n" ] }
introductory
https://codeforces.com/problemset/problem/1385/D
2,397
Consider all binary strings of length $m$ ($1 \le m \le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in total. The string $s$ is lexicographically smaller than the string $t$ (bot...
["def read_int():\n return int(input())\n\n\ndef read_ints():\n return list(map(int, input().split(' ')))\n\n\nt = read_int()\nfor case_num in range(t):\n n, m = read_ints()\n a = []\n for i in range(n):\n a.append(int(input(), 2))\n a.sort()\n k = 2 ** m - n\n ans = (k - 1) // 2\n for...
{ "inputs": [ "5\n3 3\n010\n001\n111\n4 3\n000\n111\n100\n011\n1 1\n1\n1 1\n0\n3 2\n00\n01\n10\n" ], "outputs": [ "100\n010\n0\n1\n11\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/H
2,398
You are given a table $a$ of size $2 \times n$ (i.e. two rows and $n$ columns) consisting of integers from $1$ to $n$. In one move, you can choose some column $j$ ($1 \le j \le n$) and swap values $a_{1, j}$ and $a_{2, j}$ in it. Each column can be chosen no more than once. Your task is to find the minimum number of ...
["import sys\n\nsys.setrecursionlimit(10 ** 5)\nint1 = lambda x: int(x) - 1\np2D = lambda x: print(*x, sep=\"\\n\")\ndef II(): return int(sys.stdin.readline())\ndef MI(): return map(int, sys.stdin.readline().split())\ndef LI(): return list(map(int, sys.stdin.readline().split()))\ndef LLI(rows_number): return [LI() for ...
{ "inputs": [ "6\n4\n1 2 3 4\n2 3 1 4\n5\n5 3 5 1 4\n1 2 3 2 4\n3\n1 2 1\n3 3 2\n4\n1 2 2 1\n3 4 3 4\n4\n4 3 1 4\n3 2 2 1\n3\n1 1 2\n3 2 2\n" ], "outputs": [ "0\n\n2\n2 3 \n1\n1 \n2\n3 4 \n2\n3 4 \n-1\n" ] }
introductory
https://codeforces.com/problemset/problem/1385/G
2,399
You are given a graph consisting of $n$ vertices and $m$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such...
["from sys import stdin, stdout\nimport functools\nimport sys,os,math\n\n#sys.setrecursionlimit(10**6)\n\nT = int(input())\nfor _ in range(T):\n N, M = list(map(int, input().split()))\n DS = [0] * (N + 1)\n ES = []\n g = [[] for _ in range(N + 1)]\n for _ in range(M):\n t, u, v = list(map(int, inp...
{ "inputs": [ "4\n3 1\n0 1 3\n5 5\n0 2 1\n1 1 5\n1 5 4\n0 5 2\n1 3 5\n4 5\n1 1 2\n0 4 3\n1 3 1\n0 2 3\n1 2 4\n4 5\n1 4 1\n1 1 3\n0 1 2\n1 2 4\n1 3 2\n" ], "outputs": [ "YES\n3 1\nYES\n2 1\n1 5\n5 4\n2 5\n3 5\nYES\n1 2\n3 4\n3 1\n3 2\n2 4\nNO\n" ] }
introductory
https://codeforces.com/problemset/problem/1385/E
2,400
The round carousel consists of $n$ figures of animals. Figures are numbered from $1$ to $n$ in order of the carousel moving. Thus, after the $n$-th figure the figure with the number $1$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type...
["import sys\ninput = lambda: sys.stdin.readline().rstrip()\n\nT = int(input())\nfor _ in range(T):\n N = int(input())\n A = [int(a) for a in input().split()]\n \n if max(A) == min(A):\n print(1)\n print(*([1] * N))\n elif N % 2 == 0:\n print(2)\n print(*([1, 2] * (N // 2)))\n...
{ "inputs": [ "4\n5\n1 2 1 2 2\n6\n1 2 2 1 2 2\n5\n1 2 1 2 3\n3\n10 10 10\n" ], "outputs": [ "2\n2 1 2 1 1 \n2\n1 2 1 2 1 2 \n3\n1 2 1 2 3\n1\n1 1 1 \n" ] }
introductory
https://codeforces.com/problemset/problem/1328/D
2,401
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Example 1: Input: pattern = "abba", str = "dog cat cat dog" Output: true Example 2: Input:pattern = "abba", str = "dog ca...
["class Solution:\n def wordPattern(self, pattern, str):\n \"\"\"\n :type pattern: str\n :type str: str\n :rtype: bool\n \"\"\"\n # d['a'] = word\n #pattern_arr = list(pattern)\n str_arr = str.split()\n pattern_dict = {}\n str_dict = {}...
{"fn_name": "wordPattern", "inputs": [["\"abba\"", "\"dog cat cat dog\""]], "outputs": [false]}
introductory
https://leetcode.com/problems/word-pattern/
class Solution: def wordPattern(self, pattern: str, s: str) -> bool:
2,402
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not b...
["class Solution:\n def reverseWords(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n rev_str = s[::-1]\n rev_arr = rev_str.split()\n final = rev_arr[::-1]\n \n return ' '.join(map(str, final))\n \n", "class Solution:\n def revers...
{"fn_name": "reverseWords", "inputs": [["\"Let's take LeetCode contest\""]], "outputs": ["s'teL\" ekat edoCteeL \"tsetnoc"]}
introductory
https://leetcode.com/problems/reverse-words-in-a-string-iii/
class Solution: def reverseWords(self, s: str) -> str:
2,403
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. Example: Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14 Note: The...
["class Solution:\n def checkPerfectNumber(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n perfect = set([6, 28, 496, 8128, 33550336, 8589869056])\n return num in perfect", "class Solution:\n def checkPerfectNumber(self, num):\n \"\"\"\n ...
{"fn_name": "checkPerfectNumber", "inputs": [[28]], "outputs": [true]}
introductory
https://leetcode.com/problems/perfect-number/
class Solution: def checkPerfectNumber(self, num: int) -> bool:
2,404
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Find the kth positive integer that is missing from this array.   Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive intege...
["class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n lo, hi = 0, len(arr) - 1\n while lo < hi:\n mid = hi - (hi - lo) // 2\n # mid = lo + (hi - lo) // 2\n missing = arr[mid] - mid - 1\n if missing < k:\n lo = mid\n ...
{"fn_name": "findKthPositive", "inputs": [[[2, 3, 4, 7, 11], 5]], "outputs": [9]}
introductory
https://leetcode.com/problems/kth-missing-positive-number/
class Solution: def findKthPositive(self, arr: List[int], k: int) -> int:
2,405
A robot on an infinite grid starts at point (0, 0) and faces north.  The robot can receive one of three possible types of commands: -2: turn left 90 degrees -1: turn right 90 degrees 1 <= x <= 9: move forward x units Some of the grid squares are obstacles.  The i-th obstacle is at grid point (obstacles[i][0], obstacl...
["class Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n \n obstacles = set([tuple(x) for x in obstacles])\n \n face = 0 # NESW = 0123\n x,y = 0,0\n max_dist = 0\n for command in commands:\n if command==-2:\n ...
{"fn_name": "robotSim", "inputs": [[[4, -1, 3], [[], []]]], "outputs": [25]}
introductory
https://leetcode.com/problems/walking-robot-simulation/
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
2,406
Let's call an array arr a mountain if the following properties hold: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... arr[i-1] < arr[i] arr[i] > arr[i+1] > ... > arr[arr.length - 1] Given an integer array arr that is guaranteed to be a mountain, return any i...
["class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n l,r = 0,len(arr)-1\n while l<=r:\n m = (l+r)//2\n if (arr[m]>=arr[m-1])and (arr[m]>=arr[m+1]):\n return m\n else:\n if arr[m-1]>arr[m]:\n r ...
{"fn_name": "peakIndexInMountainArray", "inputs": [[[0, 1, 0]]], "outputs": [1]}
introductory
https://leetcode.com/problems/peak-index-in-a-mountain-array/
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int:
2,407
Given an integer number n, return the difference between the product of its digits and the sum of its digits.   Example 1: Input: n = 234 Output: 15 Explanation: Product of digits = 2 * 3 * 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 Example 2: Input: n = 4421 Output: 21 Explanation: Product of digi...
["class Solution:\n def subtractProductAndSum(self, n: int) -> int:\n stringInt = str(n)\n product = 1\n sum = 0\n for i in stringInt:\n product *= int(i)\n sum += int(i) \n return product - sum", "class Solution:\n def subtractProductAndSum(self, n: int...
{"fn_name": "subtractProductAndSum", "inputs": [[234]], "outputs": [15]}
introductory
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution: def subtractProductAndSum(self, n: int) -> int:
2,408
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters.
["class Solution:\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return -1\n elif len(s) == 1:\n return 0\n \n result = len(s)\n for ch in range(ord('a'), ord('z') + 1):\n ...
{"fn_name": "firstUniqChar", "inputs": [["\"leetcode\""]], "outputs": [1]}
introductory
https://leetcode.com/problems/first-unique-character-in-a-string/
class Solution: def firstUniqChar(self, s: str) -> int:
2,409
Given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).   Example 1: Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changing the ...
["class Solution:\n def maximum69Number (self, num: int) -> int:\n numString = str(num)\n numLength = len(numString)\n firstIndex = numString.find('6')\n if firstIndex == -1:\n return num\n else:\n return num+3*10**(numLength-firstIndex-1)", "class Solution:\n...
{"fn_name": "maximum69Number", "inputs": [[9669]], "outputs": [9969]}
introductory
https://leetcode.com/problems/maximum-69-number/
class Solution: def maximum69Number (self, num: int) -> int:
2,410
Your friend is typing his name into a keyboard.  Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard.  Return True if it is possible that it was your friends name, with some characters (possibly none) bei...
["class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n name=list(name)\n typed= list(typed)\n \n while name:\n i, j=0,0\n n=name[0]\n while name and name[0]==n:\n i+=1\n name.pop(0)\n whil...
{"fn_name": "isLongPressedName", "inputs": [["\"alex\"", "\"aaleex\""]], "outputs": [true]}
introductory
https://leetcode.com/problems/long-pressed-name/
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool:
2,411
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum...
["class Solution:\n def thirdMax(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums = sorted(list(set(nums)))\n if len(nums)<3:\n return max(nums)\n else:\n return nums[-3]\n \n \n", "class Solution:...
{"fn_name": "thirdMax", "inputs": [[[3, 2, 1]]], "outputs": [1]}
introductory
https://leetcode.com/problems/third-maximum-number/
class Solution: def thirdMax(self, nums: List[int]) -> int:
2,412
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.   Exampl...
["from string import ascii_lowercase\nclass Solution:\n def removeDuplicates(self, S: str) -> str:\n \n dup = {2*ch for ch in ascii_lowercase}\n \n prev_length = -1\n \n while prev_length!=len(S):\n prev_length = len(S)\n for d in dup:\n ...
{"fn_name": "removeDuplicates", "inputs": [["\"abbaca\""]], "outputs": ["\"ca\""]}
introductory
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
class Solution: def removeDuplicates(self, S: str) -> str:
2,413
Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example: Input: 2 Output: 987 Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 Note: The range of n is [1,8].
["class Solution:\n def largestPalindrome(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n A = [0,9,987,123,597,677,1218,877,475]\n return A[n]", "class Solution:\n def largestPalindrome(self, n):\n \"\"\"\n :type n: int\n :rtype:...
{"fn_name": "largestPalindrome", "inputs": [[1]], "outputs": [9]}
introductory
https://leetcode.com/problems/largest-palindrome-product/
class Solution: def largestPalindrome(self, n: int) -> int:
2,414
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: 0 <= i < j < k < arr.length |arr[i] - arr[j]| <= a |arr[j] - arr[k]| <= b |arr[i] - arr[k]| <= c Where |x| denotes the absolute ...
["class Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n da = defaultdict(set)\n db = defaultdict(set)\n dc = defaultdict(set)\n for i in range(len(arr)-1):\n for j in range(i+1,len(arr)):\n dis = abs(arr[j]-arr[i])\n ...
{"fn_name": "countGoodTriplets", "inputs": [[[3, 0, 1, 1, 9, 7], 7, 2, 3]], "outputs": [4]}
introductory
https://leetcode.com/problems/count-good-triplets/
class Solution: def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
2,415
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6],...
["class Solution:\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n \n num=[i for i in nums if i<target]\n return len(num)", "class Solution:\n '''Complexity O(log(n))'''\n def searchI...
{"fn_name": "searchInsert", "inputs": [[[1, 3, 5, 6], 5]], "outputs": [2]}
introductory
https://leetcode.com/problems/search-insert-position/
class Solution: def searchInsert(self, nums: List[int], target: int) -> int:
2,416
Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Returns: True Example 2: Input: 14 Returns: False Credits:Special thanks to @elmirap for adding this problem and creating...
["class Solution:\n def isPerfectSquare(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n n = num**0.5\n if n == int(n):\n return True\n else:\n return False", "class Solution:\n def isPerfectSquare(self, num):\n ...
{"fn_name": "isPerfectSquare", "inputs": [[16]], "outputs": [true]}
introductory
https://leetcode.com/problems/valid-perfect-square/
class Solution: def isPerfectSquare(self, num: int) -> bool:
2,417
Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will be in range of [-1e7, 1e7].
["class Solution:\n def convertToBase7(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num < 0:\n return '-' + str(self.convertToBase7(-num))\n elif num < 7:\n return str(num)\n else:\n return str(self.conv...
{"fn_name": "convertToBase7", "inputs": [[100]], "outputs": ["202"]}
introductory
https://leetcode.com/problems/base-7/
class Solution: def convertToBase7(self, num: int) -> str:
2,418
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input...
["class Solution:\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n num_set = set(nums)\n if len(nums) == len(num_set):\n return False\n return True\n", "class Solution:\n def containsDuplicate(self...
{"fn_name": "containsDuplicate", "inputs": [[[1, 2, 3, 1]]], "outputs": [true]}
introductory
https://leetcode.com/problems/contains-duplicate/
class Solution: def containsDuplicate(self, nums: List[int]) -> bool:
2,419
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. For example, with A = "abcd" and B = "cdabcdab". Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A re...
["class Solution:\n def repeatedStringMatch(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: int\n \"\"\"\n \n if not set(B).issubset(set(A)):\n return -1\n \n max_rep = len(B) // len(A) + 3\n A_new = A\n ...
{"fn_name": "repeatedStringMatch", "inputs": [["\"abcd\"", "\"cdabcdab\""]], "outputs": [-1]}
introductory
https://leetcode.com/problems/repeated-string-match/
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int:
2,420
Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode c...
["class Solution:\n def isAnagram(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n # dic = {}\n # for item in s:\n # if item not in dic:\n # dic[item] = 1\n # else:\n # dic[it...
{"fn_name": "isAnagram", "inputs": [["\"anagram\"", "\"nagaram\""]], "outputs": [true]}
introductory
https://leetcode.com/problems/valid-anagram/
class Solution: def isAnagram(self, s: str, t: str) -> bool:
2,421
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2
["class Solution:\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n=len(nums)\n if n==1 :\n return nums[0]\n if n%2 :\n find = set(nums[0:(n//2)+1]) & set(nums[n//2:])\n else:\n ...
{"fn_name": "majorityElement", "inputs": [[[3, 2, 3]]], "outputs": [3]}
introductory
https://leetcode.com/problems/majority-element/
class Solution: def majorityElement(self, nums: List[int]) -> int:
2,422
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).   Example 1: Input: nums = [3,4,5,2] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(...
["class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if nums[0] > nums[1]:\n largest = nums[0]\n second_largest = nums[1]\n else:\n largest = nums[1]\n second_largest = nums[0]\n for i in range(2,len(nums)):\n if nums[i] > lar...
{"fn_name": "maxProduct", "inputs": [[[3, 4, 5, 2]]], "outputs": [12]}
introductory
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/
class Solution: def maxProduct(self, nums: List[int]) -> int:
2,423
Given an array of integers nums, you start with an initial positive value startValue. In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right). Return the minimum positive value of startValue such that the step by step sum is never less than 1.   Example 1: Input: n...
["class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n res = 1\n for ind,n in enumerate(nums):\n temp = 1-sum(nums[:ind+1])\n if(temp > res):\n res = temp\n return res", "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n ...
{"fn_name": "minStartValue", "inputs": [[[-3, 2, -3, 4, 2]]], "outputs": [5]}
introductory
https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/
class Solution: def minStartValue(self, nums: List[int]) -> int:
2,424
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inp...
["class Solution:\n def addStrings(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n if len(num1) < len(num2):\n num1, num2 = num2, num1\n addon = 0\n res = \"\"\n l = len(num2)\n for i...
{"fn_name": "addStrings", "inputs": [["\"0\"", "\"0\""]], "outputs": ["172"]}
introductory
https://leetcode.com/problems/add-strings/
class Solution: def addStrings(self, num1: str, num2: str) -> str:
2,425
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. Please note that the string does not contain any non-printable characters. Example: Input: "Hello, my name is John" Output: 5
["class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n return len(s.split())", "class Solution:\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n count = 0\n ...
{"fn_name": "countSegments", "inputs": [["\"Hello, my name is John\""]], "outputs": [5]}
introductory
https://leetcode.com/problems/number-of-segments-in-a-string/
class Solution: def countSegments(self, s: str) -> int:
2,426
Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i]. After this process, we have some array B. Return the smallest possible difference between the maximum value of B and the minimum value of B.   Example 1: Input: A = [1], K = 0 Output: 0 Explanation: B = [1] ...
["class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n if len(A) == 1:\n return 0\n _min = min(A)\n _max = max(A)\n if _max - K <= _min + K:\n return 0\n return _max - _min - 2*K", "class Solution:\n def smallestRangeI(self, A: List[in...
{"fn_name": "smallestRangeI", "inputs": [[[1], 0]], "outputs": [0]}
introductory
https://leetcode.com/problems/smallest-range-i/
class Solution: def smallestRangeI(self, A: List[int], K: int) -> int:
2,427
Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The input array will only contain 0 and 1. The length of inpu...
["class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if nums == []:\n return 0\n \n count = 0\n countMax =0\n for ele in nums:\n if ele == 1:\n ...
{"fn_name": "findMaxConsecutiveOnes", "inputs": [[[1, 0, 1, 1, 0, 1]]], "outputs": [2]}
introductory
https://leetcode.com/problems/max-consecutive-ones/
class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
2,428
Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4
["class Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l = len(nums)\n if l == 1:\n return nums[0]\n \n # Attempt 1 - 80%\n # nums.sort()\n # i = 0\n # while i < l...
{"fn_name": "singleNumber", "inputs": [[[2, 2, 1]]], "outputs": [1]}
introductory
https://leetcode.com/problems/single-number/
class Solution: def singleNumber(self, nums: List[int]) -> int:
2,429
A boomerang is a set of 3 points that are all distinct and not in a straight line. Given a list of three points in the plane, return whether these points are a boomerang.   Example 1: Input: [[1,1],[2,3],[3,2]] Output: true Example 2: Input: [[1,1],[2,2],[3,3]] Output: false   Note: points.length == 3 points[i].len...
["class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n x1, y1 = points[0]\n x2, y2 = points[1]\n x3, y3 = points[2]\n \n return (y2 - y1) * (x3 - x1) != (y3 - y1) * (x2 - x1)\n", "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n ...
{"fn_name": "isBoomerang", "inputs": [[[[1, 1], [2, 3], [3, 2], [], []]]], "outputs": [true]}
introductory
https://leetcode.com/problems/valid-boomerang/
class Solution: def isBoomerang(self, points: List[List[int]]) -> bool:
2,430
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. Example 3:...
["class Solution:\n def hasAlternatingBits(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n \n if n % 2 == 0:\n n = n >> 1\n \n cnt = 0\n a = n\n while (a>0):\n cnt += 1\n a = a >> 1\n ...
{"fn_name": "hasAlternatingBits", "inputs": [[5]], "outputs": [true]}
introductory
https://leetcode.com/problems/binary-number-with-alternating-bits/
class Solution: def hasAlternatingBits(self, n: int) -> bool:
2,431
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There...
["class Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n # import collections\n # unique_nums = set(nums)\n # count = 0\n # new_nums = collections.Counter(nums)\n # if k ...
{"fn_name": "findPairs", "inputs": [[[3, 1, 4, 1, 5], 2]], "outputs": [2]}
introductory
https://leetcode.com/problems/k-diff-pairs-in-an-array/
class Solution: def findPairs(self, nums: List[int], k: int) -> int:
2,432
You're now a baseball game point recorder. Given a list of strings, each string can be one of the 4 following types: Integer (one round's score): Directly represents the number of points you get in this round. "+" (one round's score): Represents that the points you get in this round are the sum of the last two vali...
["class Solution:\n def calPoints(self, ops):\n \"\"\"\n :type ops: List[str]\n :rtype: int\n \"\"\"\n sum = 0\n for i in range (len(ops)):\n op = ops[i]\n if self.isInt(op):\n sum = sum + int(op)\n elif op == 'C':\n ...
{"fn_name": "calPoints", "inputs": [[["\"5\"", "\"2\"", "\"C\"", "\"D\"", "\"+\""]]], "outputs": [0]}
introductory
https://leetcode.com/problems/baseball-game/
class Solution: def calPoints(self, ops: List[str]) -> int:
2,433
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter...
["class Solution:\n def licenseKeyFormatting(self, S, K):\n \"\"\"\n :type S: str\n :type K: int\n :rtype: str\n \"\"\"\n # count_dash = 0\n # for item in S:\n # if item == '-':\n # count_dash += 1\n \n # S_l...
{"fn_name": "licenseKeyFormatting", "inputs": [["\"5F3Z-2e-9-w\"", 4]], "outputs": ["\"5-F3Z2-E9W\""]}
introductory
https://leetcode.com/problems/license-key-formatting/
class Solution: def licenseKeyFormatting(self, S: str, K: int) -> str:
2,434
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Exa...
["class Solution:\n def isOneBitCharacter(self, bits):\n \"\"\"\n :type bits: List[int]\n :rtype: bool\n \"\"\"\n \n \"\"\"\n i = 0\n while i < len(bits)-1:\n if bits[i] == 1:\n i += 2\n \n else: ...
{"fn_name": "isOneBitCharacter", "inputs": [[[1, 0, 0]]], "outputs": [true]}
introductory
https://leetcode.com/problems/1-bit-and-2-bit-characters/
class Solution: def isOneBitCharacter(self, bits: List[int]) -> bool:
2,435
Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.     Example 1: Input: n = 4 Output: "pppz" Explanation: "pppz" is a vali...
["class Solution:\n def generateTheString(self, n: int) -> str:\n \n \n \n if n%2 == 0:\n \n return ''.join(['a']*(n-1) + ['b'])\n \n else:\n if n == 1:\n return 'a'\n else:\n return ''.join(['a']*(n-2) + ...
{"fn_name": "generateTheString", "inputs": [[4]], "outputs": ["aaab"]}
introductory
https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/
class Solution: def generateTheString(self, n: int) -> str:
2,436
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false
["class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n cleanlist = [c for c in s.lower() if c.isalnum()]\n return cleanlist == cleanlist[::-1]", "class Solution:\n def isPalindrome(self, s):\n \"\"\"\n :typ...
{"fn_name": "isPalindrome", "inputs": [["\"A man, a plan, a canal: Panama\""]], "outputs": [true]}
introductory
https://leetcode.com/problems/valid-palindrome/
class Solution: def isPalindrome(self, s: str) -> bool:
2,437
Given an array of positive integers arr,  find a pattern of length m that is repeated k or more times. A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. Retu...
["import queue\n\n\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n streak = 0\n \n for i in range(len(arr)-m):\n if arr[i] == arr[i+m]:\n streak +=1\n else:\n streak = 0\n if streak == (k-1)*m:...
{"fn_name": "containsPattern", "inputs": [[[1, 2, 4, 4, 4, 4], 1, 3]], "outputs": [true]}
introductory
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
2,438
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: "Hello World" Output: 5
["class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n x = s.split()\n return len(x[-1]) if len(x) > 0 else 0", "class Solution:\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype:...
{"fn_name": "lengthOfLastWord", "inputs": [["\"Hello World\""]], "outputs": [6]}
introductory
https://leetcode.com/problems/length-of-last-word/
class Solution: def lengthOfLastWord(self, s: str) -> int:
2,439
Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an emp...
["class Solution:\n def strStr(self, haystack, needle):\n \"\"\"\n :type haystack: str\n :type needle: str\n :rtype: int\n \"\"\"\n if haystack == \"\" and needle == \"\":\n return 0\n if needle == \"\":\n return 0\n if haystack...
{"fn_name": "strStr", "inputs": [["\"hello\"", "\"ll\""]], "outputs": [-1]}
introductory
https://leetcode.com/problems/implement-strstr/
class Solution: def strStr(self, haystack: str, needle: str) -> int:
2,440
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 ...
["class Solution:\n \n dictionary = {}\n def climbStairs(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n number = 0\n if n == 0 or n == 1:\n return 1\n if n in self.dictionary:\n return self.dictionary[n]\n el...
{"fn_name": "climbStairs", "inputs": [[2]], "outputs": [2]}
introductory
https://leetcode.com/problems/climbing-stairs/
class Solution: def climbStairs(self, n: int) -> int:
2,441
Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. To make the string good, you can choose two adjace...
["class Solution:\n def makeGood(self, s: str) -> str:\n \n stack=[]\n \n for i in s:\n if (stack!=[] and i.lower()==stack[-1].lower() and i!=stack[-1] ) :\n stack.pop()\n else:\n stack.append(i)\n return ''.join(stack)\n ...
{"fn_name": "makeGood", "inputs": [["\"leEeetcode\""]], "outputs": ["\"leetcode\""]}
introductory
https://leetcode.com/problems/make-the-string-great/
class Solution: def makeGood(self, s: str) -> str:
2,442
Given a string s. You should re-order the string using the following algorithm: Pick the smallest character from s and append it to the result. Pick the smallest character from s which is greater than the last appended character to the result and append it. Repeat step 2 until you cannot pick more characters. Pick the...
["class Solution:\n def sortString(self, s: str) -> str:\n sforward = sorted(s)\n sbackward = sforward[-1]\n \n suniq = ''\n \n for i in s:\n if i not in suniq:\n suniq += i\n\n suniq = sorted(suniq)\n \n max_count = 0\n ...
{"fn_name": "sortString", "inputs": [["\"aaaabbbbcccc\""]], "outputs": ["\"abccba\"abccba"]}
introductory
https://leetcode.com/problems/increasing-decreasing-string/
class Solution: def sortString(self, s: str) -> str:
2,443
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed.   Example 1: Input: text = "nlaebolko" Output: 1 Example 2: Input: text = "loonbalxballp...
["class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n memo = defaultdict(int)\n for t in text:\n if t in 'balon':\n memo[t] += 1\n count_once = min(memo['b'], memo['a'], memo['n'])\n count_twice = min(memo['l'], memo['o'])\n return min(cou...
{"fn_name": "maxNumberOfBalloons", "inputs": [["\"nlaebolko\""]], "outputs": [1]}
introductory
https://leetcode.com/problems/maximum-number-of-balloons/
class Solution: def maxNumberOfBalloons(self, text: str) -> int:
2,444
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0. Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their...
["class Solution:\n def binaryGap(self, n: int) -> int:\n maxDist = 0\n currDist = 0\n while n:\n if n & 1 and currDist != 0:\n maxDist = max(maxDist, currDist)\n currDist = 1\n elif n & 1:\n currDist = 1\n elif not n ...
{"fn_name": "binaryGap", "inputs": [[22]], "outputs": [2]}
introductory
https://leetcode.com/problems/binary-gap/
class Solution: def binaryGap(self, n: int) -> int:
2,445
Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in th...
["class Solution:\n def detectCapitalUse(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n if len(word) == 0:\n return True\n elif word.isupper() or word.islower():\n return True\n elif len(word) > 1:\n retur...
{"fn_name": "detectCapitalUse", "inputs": [["\"USA\""]], "outputs": [true]}
introductory
https://leetcode.com/problems/detect-capital/
class Solution: def detectCapitalUse(self, word: str) -> bool:
2,446
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. Example 1: Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: Th...
["class Solution:\n def findLHS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(nums)\n ret = 0\n for i in count:\n if i+1 in count:\n ret = max(ret, count[i]+count[i+1])\n \...
{"fn_name": "findLHS", "inputs": [[[1, 3, 2, 2, 5, 2, 3, 7]]], "outputs": [5]}
introductory
https://leetcode.com/problems/longest-harmonious-subsequence/
class Solution: def findLHS(self, nums: List[int]) -> int:
2,447
Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not include the letter "y".
["class Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n char_list = list(s)\n first, last = 0, len(char_list) - 1\n while first < last:\n ...
{"fn_name": "reverseVowels", "inputs": [["\"hello\""]], "outputs": ["\"holle\""]}
introductory
https://leetcode.com/problems/reverse-vowels-of-a-string/
class Solution: def reverseVowels(self, s: str) -> str:
2,448
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd" ...
["class Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n re = 0\n set_s = set(s)\n flag = False\n for x in set_s:\n if s.count(x) % 2 == 0:\n re += s.count(x)\n elif s....
{"fn_name": "longestPalindrome", "inputs": [["\"abccccdd\""]], "outputs": [9]}
introductory
https://leetcode.com/problems/longest-palindrome/
class Solution: def longestPalindrome(self, s: str) -> int:
2,449
Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s. Return the minimum number of steps to make the given string empty. A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing i...
["class Solution:\n def removePalindromeSub(self, s: str) -> int:\n # 'a' 1\n # 'aa' 1\n # 'ab' 2\n # 'abb' 2\n # 'aabb' 2\n # 'abba' 1\n # 'abaaba'\n \n if len(s) == 0:\n return 0\n if s == s[::-1]:\n return 1\n retur...
{"fn_name": "removePalindromeSub", "inputs": [["\"ababa\""]], "outputs": [1]}
introductory
https://leetcode.com/problems/remove-palindromic-subsequences/
class Solution: def removePalindromeSub(self, s: str) -> int:
2,450
Given an array of unique integers salary where salary[i] is the salary of the employee i. Return the average salary of employees excluding the minimum and maximum salary.   Example 1: Input: salary = [4000,3000,1000,2000] Output: 2500.00000 Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively. ...
["class Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n del salary[0]\n del salary[-1]\n return sum(salary)/len(salary)", "class Solution:\n def average(self, salary: List[int]) -> float:\n mx = 0\n mn = 100005\n sm = 0\n n = len...
{"fn_name": "average", "inputs": [[[1000, 2000, 3000, 4000]]], "outputs": [2500.0]}
introductory
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/
class Solution: def average(self, salary: List[int]) -> float:
2,451
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note:...
["class Solution:\n def canConstruct(self, ransomNote, magazine):\n \"\"\"\n :type ransomNote: str\n :type magazine: str\n :rtype: bool\n \"\"\"\n ransome = set(ransomNote)\n for i in ransome:\n if ransomNote.count(i) > magazine.count(i):\n ...
{"fn_name": "canConstruct", "inputs": [["\"a\"", "\"b\""]], "outputs": [false]}
introductory
https://leetcode.com/problems/ransom-note/
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool:
2,452
We have a collection of stones, each stone has a positive integer weight. Each turn, we choose the two heaviest stones and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is: If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally d...
["class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n while True:\n if len(stones) == 1:\n return stones[0]\n if len(stones) == 0:\n return 0\n stones.sort()\n x = stones.pop()\n y = stones.pop()\n ...
{"fn_name": "lastStoneWeight", "inputs": [[[2,7,4,1,8,1]]], "outputs": [1]}
introductory
https://leetcode.com/problems/last-stone-weight/
class Solution: def lastStoneWeight(self, stones: List[int]) -> int:
2,453
Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle wh...
["class Solution:\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n former = set()\n while True:\n h = 0\n while n > 0:\n d = n % 10\n h += (d*d)\n n = n // 10\n ...
{"fn_name": "isHappy", "inputs": [[19]], "outputs": [true]}
introductory
https://leetcode.com/problems/happy-number/
class Solution: def isHappy(self, n: int) -> bool:
2,454
Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 701 Output: "ZY"
["class Solution:\n def convertToTitle(self, n):\n \"\"\"\n :type n: int\n :rtype: str\n \"\"\"\n ans = ''\n a = 0\n \n while n>0:\n if a>0:\n n = n//26\n p = n%26\n if p==0:\n p=26\...
{"fn_name": "convertToTitle", "inputs": [[1]], "outputs": ["A"]}
introductory
https://leetcode.com/problems/excel-sheet-column-title/
class Solution: def convertToTitle(self, n: int) -> str:
2,455
Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays...
["class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: \n res=0\n for start,end in zip(startTime,endTime):\n if(queryTime>=start and queryTime<=end):\n res+=1\n return res", "class Solution:\n def busyStudent(self,...
{"fn_name": "busyStudent", "inputs": [[[1, 2, 3], [3, 2, 7], 4]], "outputs": [1]}
introductory
https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/
class Solution: def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
2,456
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "...
["class Solution:\n def backspaceCompare(self, S1, S2):\n i1 = len(S1) - 1 \n i2 = len(S2) - 1\n \n while i1 >= 0 or i2 >= 0:\n c1 = ''\n c2 = ''\n if i1 >= 0:\n c1, i1 = self.getChar(S1, i1)\n if i2 >= 0:\n c2, i2 ...
{"fn_name": "backspaceCompare", "inputs": [["\"ab#c\"", "\"ad#c\""]], "outputs": [true]}
introductory
https://leetcode.com/problems/backspace-string-compare/
class Solution: def backspaceCompare(self, S: str, T: str) -> bool:
2,457
Given an array of integers nums, write a method that returns the "pivot" index of this array. We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. If no such index exists, we should return -1. If there are multiple p...
["class Solution:\n def pivotIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n left, right = 0, sum(nums)\n for index, num in enumerate(nums):\n right -= num\n if left == right:\n return index\n ...
{"fn_name": "pivotIndex", "inputs": [[[1, 7, 3, 6, 5, 6]]], "outputs": [3]}
introductory
https://leetcode.com/problems/find-pivot-index/
class Solution: def pivotIndex(self, nums: List[int]) -> int:
2,458
Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings.   Example 1: Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", ea...
["class Solution:\n def balancedStringSplit(self, s: str) -> int:\n lCount = rCount = 0\n retVal = 0\n \n for char in s:\n if char == 'R':\n rCount += 1\n else:\n lCount += 1\n \n if rCount == lCount:\n ...
{"fn_name": "balancedStringSplit", "inputs": [["\"RLRRLLRLRL\""]], "outputs": [5]}
introductory
https://leetcode.com/problems/split-a-string-in-balanced-strings/
class Solution: def balancedStringSplit(self, s: str) -> int:
2,459
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; oth...
["class Solution:\n def toHex(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n if num==0:\n return \"0\"\n res,n=[],0\n nums=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']\n while n<8 and num!=0:\n ...
{"fn_name": "toHex", "inputs": [[26]], "outputs": ["1a"]}
introductory
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
class Solution: def toHex(self, num: int) -> str:
2,460
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 def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # i = 0\n # i_keep = 0\n # j = 1\n # j_keep = 1\n # max_sum = nums[0]-1\n # while j < len(nums) and i < j:\n # temp_s...
{"fn_name": "maxSubArray", "inputs": [[[-2, 1, -3, 4, -1, 2, 1, -5, 4]]], "outputs": [6]}
introductory
https://leetcode.com/problems/maximum-subarray/
class Solution: def maxSubArray(self, nums: List[int]) -> int: